package ru.yandex.webmaster3.viewer.http.turbo.sandbox;

import java.util.UUID;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

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.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.error.TurboErrorType;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.download.DownloadStatus;
import ru.yandex.webmaster3.storage.turbo.dao.TurboDownloadTask;
import ru.yandex.webmaster3.storage.turbo.dao.TurboDownloadTasksYDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.viewer.http.turbo.sandbox.GetTurboErrorContentAction.Request;

/**
 * Created by Oleg Bazdyrev on 19/04/2018.
 */
@ReadAction
@Category("turbo")
@Description("Получение текста ошибки")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetTurboErrorContentAction extends AbstractUserVerifiedHostAction<Request, GetTurboErrorContentResponse> {

    private final TurboDownloadTasksYDao turboDownloadTasksYDao;

    @Override
    public GetTurboErrorContentResponse process(Request request) {
        try {
            TurboDownloadTask task = turboDownloadTasksYDao.getTask(request.taskId);
            if (task == null) {
                return GetTurboErrorContentResponse.createErrorResponse(TurboErrorType.INTERNAL);
            }
            if (task.getStatus() == DownloadStatus.INTERNAL_ERROR) {
                return GetTurboErrorContentResponse.createErrorResponse(task.getError());
            }

            return new GetTurboErrorContentResponse.NormalResponse(task.getStatus(), task.getFeedType(), task.getContent());
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Cassandra error",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }

    public static final class Request extends AbstractUserVerifiedHostRequest {

        private UUID taskId;

        @RequestQueryProperty(required = true)
        @Description("Идентификатор задачи с результатов поиска текста ошибки")
        public void setTaskId(UUID taskId) {
            this.taskId = taskId;
        }
    }

}
