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.XmlLimitsService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.util.scheduler.timetable.AbstractLockableTaskExecutor;

import java.util.concurrent.TimeUnit;

/**
 * User: azakharov
 * Date: 31.10.12
 * Time: 14:15
 */
public class UpdateLimitsTask extends AbstractLockableTaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(UpdateLimitsTask.class);

    private static final String LOCK_NAME = "update_xml_limits";
    private XmlLimitsService xmlLimitsService;

    @Override
    public String runWithRELogging(ExecutionContext context) throws InternalException {
        log.debug("UpdateLimitsTask started");

        if (!getLock(WMCPartition.nullPartition(), LOCK_NAME, 60)) {
            String message = "Failed to get lock for task: " + this.getClass().getSimpleName();
            log.warn(message);
            return message;
        }

        try {
            long t1 = System.nanoTime();
//            xmlLimitsService.fixMissingHostLimitDelegations();
            long t2 = System.nanoTime();
            log.debug("UpdateLimitsTask processing time is " + TimeUnit.NANOSECONDS.toMillis(t2 - t1) + " ms");
        } finally {
            releaseLock(WMCPartition.nullPartition(), LOCK_NAME);
        }
        return "UpdateLimitsTask executed successfully";
    }

    @Required
    public void setXmlLimitsService(XmlLimitsService xmlLimitsService) {
        this.xmlLimitsService = xmlLimitsService;
    }
}
