package ru.yandex.webmaster3.viewer.http.sitemap.analyze;

import com.datastax.driver.core.utils.UUIDs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.http.FileParameterTransfer;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.UrlUtils;
import ru.yandex.webmaster3.core.worker.task.sitemap.SitemapAnalysisTaskData;
import ru.yandex.webmaster3.storage.async.model.AsyncTaskType;
import ru.yandex.webmaster3.storage.sitemap.service.AnalyzeSitemapActionService;
import ru.yandex.webmaster3.storage.async.AsyncRequestTaskService;
import ru.yandex.webmaster3.storage.sitemap.service.model.AnalyzeSitemapInputData;
import ru.yandex.webmaster3.storage.tools.ToolType;
import ru.yandex.webmaster3.storage.tools.ToolsRequestsLimitService;
import ru.yandex.webmaster3.viewer.http.BaseWebmaster3Action;
import ru.yandex.webmaster3.viewer.http.sitemap.analyze.model.AnalyzeSitemapRequest;
import ru.yandex.webmaster3.viewer.http.sitemap.analyze.model.StartSitemapAnalyzeErrorTypes;
import ru.yandex.webmaster3.viewer.http.sitemap.analyze.model.StartSitememapAnalyzeResponse;
import ru.yandex.wmtools.common.util.URLUtil;

import java.net.URL;
import java.util.UUID;

/**
 * @author: ishalaru
 * DATE: 13.05.2019
 */
@ReadAction
@Description(value = "Создать заявку на валидацию файлов sitemap")
@Category("sitemap")
@Slf4j
@Component("/sitemap/startAnalyze")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class StartAnalyzeSitemapAction extends BaseWebmaster3Action<AnalyzeSitemapRequest, StartSitememapAnalyzeResponse> {

    private final AsyncRequestTaskService asyncRequestTaskService;
    private final ToolsRequestsLimitService toolsRequestsLimitService;

    @Override
    public StartSitememapAnalyzeResponse process(AnalyzeSitemapRequest request) {
        FileParameterTransfer transferFile =
                AnalyzeSitemapActionService.convert(request.getSitemapFile());
        AnalyzeSitemapInputData analyzeSitemapInputData =
                new AnalyzeSitemapInputData(request.getSitemapText(), request.getSitemapUrl(), transferFile);

        StartSitemapAnalyzeErrorTypes errorTypes = fastValidation(analyzeSitemapInputData);
        if (errorTypes != null) {
            return new StartSitememapAnalyzeResponse.UniversalResponse(errorTypes);
        }
        UUID taskId = UUIDs.timeBased();
        SitemapAnalysisTaskData sitemapAnalysisTaskData = new SitemapAnalysisTaskData(taskId, request.getSitemapText(), request.getSitemapUrl(), transferFile);

        if (!toolsRequestsLimitService.tryRequest(request.getUserId(), analyzeSitemapInputData.getSitemapUrl(), ToolType.SITEMAP)) {
            return new StartSitememapAnalyzeResponse.RequestsLimitExceededResponse();
        }
        toolsRequestsLimitService.addUserRequest(request.getUserId(), analyzeSitemapInputData.getSitemapUrl(), ToolType.SITEMAP);

        AsyncRequestTaskService.CreateRequestResult requestResult =
                asyncRequestTaskService.createRequest(AsyncTaskType.ANALYZE_SITEMAP_ACTION, 1, analyzeSitemapInputData, sitemapAnalysisTaskData);

        return new StartSitememapAnalyzeResponse.NormalResponse(requestResult.getRequestId());
    }

    public StartSitemapAnalyzeErrorTypes fastValidation(AnalyzeSitemapInputData inputData) {
        if (inputData.getSitemapText() != null) {
            if (inputData.getSitemapText() == null || inputData.getSitemapText().isBlank()) {
                return StartSitemapAnalyzeErrorTypes.START_SITEMAP_ANALYZE_INVALID_INPUT_TEXT;
            }
        } else if (inputData.getSitemapUrl() != null) {
            URL url;
            try {
                url = UrlUtils.prepareUrl(inputData.getSitemapUrl(), true);
            } catch (IllegalArgumentException e) {
                return StartSitemapAnalyzeErrorTypes.START_SITEMAP_ANALYZE_INVALID_URL;
            }
            if (URLUtil.isHomePage(url)) {
                return StartSitemapAnalyzeErrorTypes.START_SITEMAP_ANALYZE_URL_IS_HOMEPAGE;
            }
        } else if (inputData.getSitemapFile() != null) {
            if (inputData.getSitemapFile().getSize() == 0) {
                return StartSitemapAnalyzeErrorTypes.START_SITEMAP_ANALYZE_INVALID_FILE_PATH;
            }
        } else {
            return StartSitemapAnalyzeErrorTypes.START_SITEMAP_ANALYZE_INVALID_INPUT_DATA;
        }
        return null;
    }
}

