package ru.yandex.webmaster3.monitoring.solomon.trigger.actions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
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.ReadAction;
import ru.yandex.webmaster3.monitoring.solomon.WebmasterTriggersService;
import ru.yandex.webmaster3.monitoring.solomon.api.SolomonControlApiV2Service;
import ru.yandex.webmaster3.monitoring.solomon.trigger.actions.GetAlertsListAction.Request;
import ru.yandex.webmaster3.monitoring.solomon.trigger.actions.GetAlertsListAction.Response;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Oleg Bazdyrev on 13/06/2017.
 */
@ReadAction
public class GetAlertsListAction extends Action<Request, Response> {
    private static final Logger log = LoggerFactory.getLogger(GetAlertsListAction.class);

    private WebmasterTriggersService webmasterTriggersService;
    private SolomonControlApiV2Service solomonControlApiV2Service;

    @Override
    public Response process(Request request) throws WebmasterException {
        List<TriggerCategory> triggerCategories = webmasterTriggersService.listTriggers()
                .stream()
                .map(trigger -> new TriggerCategory(trigger.getId(), trigger.getDashboardCategory()))
                .sorted(Comparator.comparing(TriggerCategory::getCategory).thenComparing(TriggerCategory::getId))
                .collect(Collectors.toList());

        return new Response(triggerCategories);
    }

    public static class Request implements ActionRequest {
    }

    public static class Response implements ActionResponse.NormalResponse {

        private final List<TriggerCategory> triggerCategories;

        public Response(List<TriggerCategory> triggerCategories) {
            this.triggerCategories = triggerCategories;
        }

        public List<TriggerCategory> getTriggerCategories() {
            return triggerCategories;
        }
    }

    public static class TriggerCategory {

        private final String id;
        private final String category;

        public TriggerCategory(String id, String category) {
            this.id = id;
            this.category = category;
        }

        public String getId() {
            return id;
        }

        public String getCategory() {
            return category;
        }
    }

    @Required
    public void setWebmasterTriggersService(WebmasterTriggersService webmasterTriggersService) {
        this.webmasterTriggersService = webmasterTriggersService;
    }

    @Required
    public void setSolomonControlApiV2Service(SolomonControlApiV2Service solomonControlApiV2Service) {
        this.solomonControlApiV2Service = solomonControlApiV2Service;
    }
}
