package ru.yandex.wmconsole.periodic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.scheduler.ExecutionContext;
import ru.yandex.wmconsole.data.partition.WMCPartition;
import ru.yandex.wmconsole.service.dao.TblRobotdbInfoDao;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.util.scheduler.timetable.AbstractTaskExecutor;

/**
 * @author baton
 */
public class CheckHungUpdateTask extends AbstractTaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(CheckHungUpdateTask.class);

    private TblRobotdbInfoDao tblRobotdbInfoDao;

    @Override
    public String runWithRELogging(ExecutionContext context) {
        log.debug("CheckHungUpdateTask task fired");

        String msg;
        try {
            int dbCount = WMCPartition.getHostDbCount(getDatabaseCount());
            for (int databaseIndex = 0; databaseIndex < dbCount; databaseIndex++) {
                logConnections(databaseIndex);
                tblRobotdbInfoDao.updateStateToNew(databaseIndex);
                logConnections(databaseIndex);
            }

            msg = "CheckHungUpdateTask task OK";
            log.debug(msg);
        } catch (InternalException e) {
            msg = "CheckHungUpdateTask task failed";
            log.error(msg, e);
        }
        return msg;
    }

    @Required
    public void setTblRobotdbInfoDao(TblRobotdbInfoDao tblRobotdbInfoDao) {
        this.tblRobotdbInfoDao = tblRobotdbInfoDao;
    }
}
