package ru.yandex.webmaster3.worker.http.periodic;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.*;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskInfo;
import ru.yandex.webmaster3.core.worker.task.PeriodicTaskType;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.worker.PeriodicTask;
import ru.yandex.webmaster3.worker.TaskRegistry;

/**
 * @author aherman
 */
public class GetPeriodicTaskStateAction extends Action<GetPeriodicTaskStateAction.Request, GetPeriodicTaskStateAction.Response> {

    private final ApplicationContext applicationContext;
    private final TaskRegistry taskRegistry;

    @Autowired
    public GetPeriodicTaskStateAction(ApplicationContext applicationContext, TaskRegistry taskRegistry) {
        this.applicationContext = applicationContext;
        this.taskRegistry = taskRegistry;
    }

    @Override
    public Response process(Request request) throws WebmasterException {
        PeriodicTask pt = taskRegistry.getPeriodicTaskRegistryMap().getOrDefault(request.getTaskType(), null);
        if (pt == null) {
            throw new WebmasterException("Error running task",
                    new WebmasterErrorResponse.InternalUnknownErrorResponse(this.getClass(), "this is not a periodic task"));
        }
        return new Response(pt.getState(), pt.isRunning(), pt.getSchedule().toString(), pt.getLastStarted(),
                pt.getLastFinished(), pt.getLastRunTimeMs(), pt.getLastResult());
    }

    public static class Request implements ActionRequest {
        private PeriodicTaskType taskType;

        public PeriodicTaskType getTaskType() {
            return taskType;
        }

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

    public static class Response extends PeriodicTaskInfo implements ActionResponse.NormalResponse {

        public Response(Object state, boolean running, String schedule, DateTime lastStarted, DateTime lastFinished,
                        long lastRunTimeMs, TaskResult lastResult) {
            super(state, running, schedule, lastStarted, lastFinished, lastRunTimeMs, lastResult);
        }
    }
}
