package ru.yandex.webmaster3.worker.messages;

import java.util.UUID;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.worker.task.PeriodicTaskState;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskType;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.storage.user.dao.UserMessages3CHDao;
import ru.yandex.webmaster3.storage.user.dao.UserMessages4CHDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.MergeFromTempTableService;
import ru.yandex.webmaster3.worker.PeriodicTask;
import ru.yandex.webmaster3.worker.TaskSchedule;

/**
 * Created by kravchenko99 on 16.10.19.
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component
public class MergeMdbUserMessages3Task extends PeriodicTask<PeriodicTaskState> {
    private final UserMessages3CHDao mdbUserMessages3CHDao;
    private final UserMessages4CHDao mdbUserMessages4CHDao;
    private final MergeFromTempTableService mdbMergeFromTempTableService;

    @Override
    public Result run(UUID runId) throws Exception {
        try {
            mdbMergeFromTempTableService.mergeFrom(mdbUserMessages3CHDao.getUserMessagesObjectsCHDao());
            try {
                mdbMergeFromTempTableService.mergeFrom(mdbUserMessages4CHDao.getUserMessagesObjectsCHDao());
            } catch (Exception e) {
                log.error("NEW_USER_MESSAGES error", e);
            }
        } finally {
            mdbMergeFromTempTableService.mergeFrom(mdbUserMessages3CHDao.getUserMessagesUpdatesCHDao());
            try {
                mdbMergeFromTempTableService.mergeFrom(mdbUserMessages4CHDao.getUserMessagesUpdatesCHDao());
            } catch (Exception e) {
                log.error("NEW_USER_MESSAGES error", e);
            }
        }

        return new Result(TaskResult.SUCCESS);
    }

    @Override
    public PeriodicTaskType getType() {
        return PeriodicTaskType.MDB_MERGE_USER_MESSAGES3;
    }

    @Override
    public TaskSchedule getSchedule() {
        return TaskSchedule.startByCron("0 */5 * * * *");
    }
}

