package ru.yandex.webmaster3.storage.host.service;

import java.util.Arrays;
import java.util.Collection;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.worker.client.WorkerClient;
import ru.yandex.webmaster3.core.worker.task.InitializeHostTaskData;
import ru.yandex.webmaster3.storage.checklist.dao.ChecklistPageSamplesYDao;
import ru.yandex.webmaster3.storage.checklist.dao.CleanableProblemsYDao;
import ru.yandex.webmaster3.storage.checklist.dao.RealTimeSiteProblemsYDao;
import ru.yandex.webmaster3.storage.checklist.dao.SiteProblemsRecheckYDao;
import ru.yandex.webmaster3.storage.host.dao.HostRobotsTxtInfoYDao;
import ru.yandex.webmaster3.storage.host.dao.HostsYDao;
import ru.yandex.webmaster3.storage.robotstxt.RobotsTxtHistoryYDao;

/**
 * @author aherman
 */
@Slf4j
@Service("hostService")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class HostService {

    private final ChecklistPageSamplesYDao checklistPageSamplesYDao;
    private final CleanableProblemsYDao cleanableProblemsYDao;
    private final HostRobotsTxtInfoYDao hostRobotsTxtInfoYDao;
    private final HostsYDao hostsYDao;
    private final RealTimeSiteProblemsYDao realTimeSiteProblemsYDao;
    private final RobotsTxtHistoryYDao robotsTxtHistoryYDao;
    private final SiteProblemsRecheckYDao siteProblemsRecheckYDao;
    private final WorkerClient workerClient;

    public boolean isHostAdded(WebmasterHostId hostId) {
        return hostsYDao.isHostAdded(hostId);
    }

    public void addHost(WebmasterHostId webmasterHostId) {
        hostsYDao.addHost(webmasterHostId, DateTime.now());
        workerClient.enqueueTask(new InitializeHostTaskData(webmasterHostId));
    }

    // метод для удаления батчами( переезд на ydao)
    public void cleanUnverifiedHosts(Collection<WebmasterHostId> hostIds) {
        hostsYDao.deleteHosts(hostIds);
        cleanableProblemsYDao.deleteProblems(hostIds, Arrays.asList(SiteProblemTypeEnum.values()));
        realTimeSiteProblemsYDao.deleteProblems(hostIds, Arrays.asList(SiteProblemTypeEnum.values()));
        checklistPageSamplesYDao.deleteSamples(hostIds);
        robotsTxtHistoryYDao.delete(hostIds);
        hostRobotsTxtInfoYDao.deleteInfos(hostIds);
        siteProblemsRecheckYDao.delete(hostIds, Arrays.asList(SiteProblemTypeEnum.values()));
    }
}
