package ru.yandex.webmaster3.viewer.http.util;

import java.util.UUID;

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.WebmasterException;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.async.AsyncRequestTaskService;
import ru.yandex.webmaster3.storage.async.model.AsyncTaskType;
import ru.yandex.webmaster3.storage.tools.ToolType;
import ru.yandex.webmaster3.storage.tools.ToolsRequestsLimitService;
import ru.yandex.webmaster3.viewer.http.BaseWebmaster3Action;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.uri.WebmasterUriUtils;

/**
 * @author: ishalaru
 * DATE: 20.05.2019
 */
@ReadAction
@Description(value = "Оставить заявку на скачивание страницы с сайта пользователя через Ситу")
@Category("validation")
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Component("/util/serverResponse/start")
public class StartServerResponseUtilAction extends BaseWebmaster3Action<ServerResponseUtilRequest, StartServerResponseUtilResponse> {
    private static final String PARAM_URL = "url";
    private final AsyncRequestTaskService asyncRequestTaskService;
    private final ToolsRequestsLimitService toolsRequestsLimitService;

    @Override
    public StartServerResponseUtilResponse process(ServerResponseUtilRequest request) {
        UUID taskId = UUIDs.timeBased();
        String urlS = request.getUrl();
        try {
            WebmasterUriUtils.toOldUri(urlS);
        } catch (UserException | NullPointerException e) {
            throw new WebmasterException("Unable to parse url: " + urlS,
                    new WebmasterErrorResponse.IllegalParameterValueResponse(this.getClass(), PARAM_URL, urlS));
        }

        if (!toolsRequestsLimitService.tryRequest(request.getUserId(), request.getUrl(), ToolType.SERVER_RESPONSE)) {
            return new StartServerResponseUtilResponse.RequestsLimitExceededErrorResponse();
        }
        toolsRequestsLimitService.addUserRequest(request.getUserId(), request.getUrl(), ToolType.SERVER_RESPONSE);

        AsyncRequestTaskService.CreateRequestResult result = asyncRequestTaskService.createRequest(AsyncTaskType.SERVER_ANSWER, 1, request.create(), request.create(taskId));
        return new StartServerResponseUtilResponse.NormalResponse(result.getRequestId());
    }
}
