package ru.yandex.webmaster3.worker.serplinks;

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

import ru.yandex.webmaster3.core.checklist.data.SiteProblemContent;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemState;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.worker.task.SerpLinksCheckerTaskData;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.storage.checklist.data.ProblemSignal;
import ru.yandex.webmaster3.storage.checklist.service.SiteProblemsService;
import ru.yandex.webmaster3.storage.serplinks.W3SerpLinksService;
import ru.yandex.webmaster3.worker.Task;

/**
 * @author avhaliullin
 */
@Category("serplinks")
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SerpLinksCheckerTask extends Task<SerpLinksCheckerTaskData> {
    private final W3SerpLinksService w3SerpLinksService;
    private final SiteProblemsService siteProblemsService;

    @Override
    public Result run(SerpLinksCheckerTaskData data) throws Exception {
        ProblemSignal problem;
        if (w3SerpLinksService.getSections(data.getHostId()).isEmpty()) {
            problem = new ProblemSignal(new SiteProblemContent.NoSerpLinks(), DateTime.now());
        } else {
            problem = new ProblemSignal(SiteProblemTypeEnum.NO_SERPLINKS, SiteProblemState.ABSENT, DateTime.now());
        }
        siteProblemsService.updateRealTimeProblem(data.getHostId(), problem);
        return new Result(TaskResult.SUCCESS);
    }

    @Override
    public Class<SerpLinksCheckerTaskData> getDataClass() {
        return SerpLinksCheckerTaskData.class;
    }

}
