package ru.yandex.webmaster3.worker.feeds;

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

import ru.yandex.webmaster3.core.feeds.mbi.ChangeRevokeStatusException;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.core.worker.task.feeds.ProcessingAddFeedTaskData;
import ru.yandex.webmaster3.storage.async.AsyncRequestTaskService;
import ru.yandex.webmaster3.storage.async.model.HttpAsyncRequestInfoResultType;
import ru.yandex.webmaster3.storage.feeds.FeedsService;
import ru.yandex.webmaster3.storage.robotstxt.model.AnalyzeRobotsTxtResponseType;
import ru.yandex.webmaster3.worker.Task;
import ru.yandex.webmaster3.worker.queue.TaskQueueMetrics;

/**
 * @author: ishalaru
 * DATE: 20.05.2019
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class AddFeedProcessingTask extends Task<ProcessingAddFeedTaskData> {
    private static final int MAX_CONCURRENT_TASKS = 100;

    private final AsyncRequestTaskService asyncRequestTaskService;
    private final FeedsService feedsService;

    @Override
    public Result run(ProcessingAddFeedTaskData data) throws Exception {
        asyncRequestTaskService.startWorkingTask(data.getRequestId());
        try {
            String domain = WwwUtil.cutWWWAndM(data.getHostId());
            FeedsService.ZoraCheckResult result = feedsService.checkUrl(data.getUrl(), data.getLogin(), data.getPassword());

            if (result == FeedsService.ZoraCheckResult.OK) {
                try {
                    feedsService.addFeed(domain, data.getUrl(), data.getRegionsId(),
                            data.getUserId(), data.getLogin(), data.getPassword(),
                            data.getType(), data.getEnabledServiceTypes());
                } catch (ChangeRevokeStatusException e) {
                    log.info("feed with url - {} and domain - {} is banned", data.getUrl(), domain);
                    result = FeedsService.ZoraCheckResult.BANNED;
                }
            }
            asyncRequestTaskService.finishWorkingTask(data.getRequestId(),
                    AnalyzeRobotsTxtResponseType.NORMAL.getValue(), result);
        } catch (Exception exp) {
            log.error("AddFeed task failed.", exp);
            asyncRequestTaskService.finishWorkingTask(data.getRequestId(),
                    HttpAsyncRequestInfoResultType.INTERNAL_ERROR);
            return new Result(TaskResult.FAIL);
        }
        return new Result(TaskResult.SUCCESS);
    }


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


    @Override
    public float getPriority(TaskQueueMetrics.TaskStatistics stats) {
        if (stats.getProcessing() >= MAX_CONCURRENT_TASKS) {
            return 0;
        } else {
            return super.getPriority(stats);
        }
    }

}
