package ru.yandex.webmaster3.importer.http;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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.core.http.WriteAction;
import ru.yandex.webmaster3.storage.importer.dao.ClickhouseImportDefinitionsYDao;
import ru.yandex.webmaster3.storage.importer.dao.ClickhouseImportTasksYDao;
import ru.yandex.webmaster3.storage.importer.model.ImportDefinition;
import ru.yandex.webmaster3.storage.importer.model.ImportTask;

/**
 * Created by Oleg Bazdyrev on 06/10/2020.
 */
@WriteAction
@Component("/import/updateTaskDefinition")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UpdateTaskDefinitionAction extends Action<UpdateTaskDefinitionAction.Request, UpdateTaskDefinitionAction.Response> {

    private final ClickhouseImportDefinitionsYDao clickhouseImportDefinitionsYDao;
    private final ClickhouseImportTasksYDao clickhouseImportTasksYDao;

    @Override
    public Response process(Request request) throws WebmasterException {
        ImportDefinition definition = clickhouseImportDefinitionsYDao.get(request.id);
        ImportTask task = clickhouseImportTasksYDao.get(request.id);
        if (definition != null && task != null) {
            clickhouseImportTasksYDao.update(task.withDefinition(definition));
            return new Response(true);
        }
        return new Response(false);
    }

    public static final class Request implements ActionRequest {
        @Setter(onMethod_ = @RequestQueryProperty(required = true))
        String id;
    }

    @Value
    public static final class Response implements ActionResponse.NormalResponse {
        boolean updated;
    }
}
