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

import org.joda.time.Duration;
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.WriteAction;
import ru.yandex.webmaster3.core.solomon.metric.SolomonKey;
import ru.yandex.webmaster3.monitoring.solomon.WebmasterTriggersService;
import ru.yandex.webmaster3.monitoring.solomon.trigger.data.TimingsTrigger;
import ru.yandex.webmaster3.monitoring.solomon.trigger.data.WebmasterTriggerInfo;

/**
 * Created by ifilippov5 on 12.06.18.
 */
@WriteAction
public class CopyTriggerAction extends Action<CopyTriggerRequest, CopyTriggerResponse> {
    private WebmasterTriggersService webmasterTriggersService;

    @Override
    public CopyTriggerResponse process(CopyTriggerRequest request) throws WebmasterException {
        String sourceTriggerId = request.getSourceTriggerId();
        WebmasterTriggerInfo sourceTriggerInfo = webmasterTriggersService.getTriggerInfo(sourceTriggerId);
        if (sourceTriggerInfo == null) {
            return new CopyTriggerResponse.SourceTriggerNotExists();
        }

        if (webmasterTriggersService.getTriggerInfo(request.getNewTriggerId()) != null) {
            return new CopyTriggerResponse.TriggerAlreadyExists();
        }

        WebmasterTriggerInfo newTriggerInfo = sourceTriggerInfo.withId(request.getNewTriggerId()).withName(request.getName());
        if (request.getDashboardCategory() != null) {
            newTriggerInfo = newTriggerInfo.withDashboardCategory(request.getDashboardCategory());
        }
        if (request.getAction() != null || request.getCategory() != null) {
            SolomonKey commonLabels = newTriggerInfo.getCommonLabels();
            if (request.getAction() != null) {
                commonLabels = commonLabels.withLabel("action", request.getAction());
            }
            if (request.getCategory() != null) {
                commonLabels = commonLabels.withLabel("category", request.getCategory());
            }
            newTriggerInfo = newTriggerInfo.withCommonLabels(commonLabels);
        }
        if (request.getDurationThreshold() != null) {
            TimingsTrigger trigger = ((TimingsTrigger) newTriggerInfo.getTrigger()).withDurationThreshold(Duration.parse(request.getDurationThreshold()));
            newTriggerInfo = newTriggerInfo.withTrigger(trigger);
        }

        webmasterTriggersService.updateTrigger(newTriggerInfo);
        webmasterTriggersService.syncRemoteTrigger(newTriggerInfo.getId());
        return new CopyTriggerResponse.NormalResponse();
    }

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