package ru.yandex.wmconsole.periodic;

import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.ReadablePeriod;
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.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.util.scheduler.timetable.AbstractTaskExecutor;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class DeleteOldDataTask extends AbstractTaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(DeleteOldDataTask.class);

    private static final String DELETE_USER_REQUESTS_INFO_QUERY =
            "DELETE FROM " +
                    "    tbl_user_requests_count " +
                    "WHERE " +
                    "    request_date <= ?";

    private ReadablePeriod deleteOlderThanPeriod = Days.days(45);

    @Override
    public String runWithRELogging(ExecutionContext context) {
        log.debug("DeleteOldDataTask task fired");
        DateMidnight deleteOlderThanDate = DateTime.now().minus(deleteOlderThanPeriod).toDateMidnight();

        int updated;

        logUserDbConnections();
        String msg;
        try {
            log.debug("Deleting tbl_user_requests_count for date " + deleteOlderThanDate.toString() + " and before...");
            updated = getJdbcTemplate(WMCPartition.nullPartition()).update(DELETE_USER_REQUESTS_INFO_QUERY,
                    deleteOlderThanDate.toDate());
            msg = "Deleting tbl_user_requests_count finished. Rows updated: " + updated;
            log.debug(msg);
        } catch (InternalException e) {
            msg = "DeleteOldDataTask:RequestsCount task failed";
            log.error(msg, e);
        }
        logUserDbConnections();
        log.debug("DeleteOldDataTask task finished");
        return msg;
    }

    @Required
    public void setDeleteOlderThanDays(int days) {
        this.deleteOlderThanPeriod = Days.days(days);
    }
}
