package ru.yandex.webmaster3.worker.http;

import lombok.RequiredArgsConstructor;
import org.joda.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ActionRequest;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.storage.searchurl.offline.dao.SearchBaseImportTablesYDao;
import ru.yandex.webmaster3.storage.searchurl.offline.data.SearchBaseImportInfo;
import ru.yandex.webmaster3.storage.searchurl.offline.data.SearchBaseImportTaskType;

/**
 * @author avhaliullin
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SearchBaseImportTogglePauseAction extends Action<SearchBaseImportTogglePauseAction.Request, SearchBaseImportTogglePauseAction.Response> {
    private final SearchBaseImportTablesYDao searchBaseImportTablesYDao;

    @Override
    public Response process(Request request) throws WebmasterException {
        SearchBaseImportInfo baseImportInfo = searchBaseImportTablesYDao.getBaseInfo(request.getTaskType(), request.baseDate);
        if (baseImportInfo == null) {
            throw new RuntimeException("Import task not found");
        }
        if (baseImportInfo.isPaused() != request.isPause()) {
            searchBaseImportTablesYDao.updateTaskPaused(request.getTaskType(), request.getBaseDate(), request.isPause());
        }
        return new Response();
    }

    public static class Request implements ActionRequest {
        private SearchBaseImportTaskType taskType;
        private Instant baseDate;
        private boolean pause = true;

        public boolean isPause() {
            return pause;
        }

        @RequestQueryProperty(required = true)
        public void setPause(boolean pause) {
            this.pause = pause;
        }

        public SearchBaseImportTaskType getTaskType() {
            return taskType;
        }

        @RequestQueryProperty(required = true)
        public void setTaskType(SearchBaseImportTaskType taskType) {
            this.taskType = taskType;
        }

        public Instant getBaseDate() {
            return baseDate;
        }

        @RequestQueryProperty(required = true)
        public void setBaseDate(Instant baseDate) {
            this.baseDate = baseDate;
        }
    }

    public static class Response implements ActionResponse.NormalResponse {
    }

}
