package ru.yandex.webmaster3.viewer.http.abt;

import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.data.WebmasterUser;
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.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.abt.AbtService;
import ru.yandex.webmaster3.storage.abt.model.SimpleExperiment;
import ru.yandex.webmaster3.storage.user.service.UserHostsService;

/**
 * Работает как abt/list с деталями экспериментов
 */
@ReadAction
@Category("abt")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("/abt/listDetailsVerifiedHost")
public class GetExperimentsDetailsVerifiedHostAction extends Action<GetExperimentsDetailsVerifiedHostAction.Req, GetExperimentsDetailsVerifiedHostAction.Res> {
    private final AbtService abtService;
    private final UserHostsService userHostsService;

    @Override
    public GetExperimentsDetailsVerifiedHostAction.Res process(GetExperimentsDetailsVerifiedHostAction.Req request) {
        long userId = request.getUserId();
        WebmasterHostId hostId = request.getHostId();
        Map<String, String> experiments = abtService.getUserExperiments(userId);
        if (hostId != null && userHostsService.getVerifiedHost(new WebmasterUser(userId), hostId) != null) {
            experiments.putAll(abtService.getHostExperiments(hostId));
        }

        Map<String, SimpleExperiment> simpleExperiments = abtService.listAllExperiments();
        simpleExperiments.keySet().retainAll(experiments.keySet());

        return new GetExperimentsDetailsVerifiedHostAction.Res(simpleExperiments);
    }

    @Getter
    public static class Req implements ActionRequest {
        private long userId;
        private WebmasterHostId hostId;

        @Description("Идентификатор хоста")
        @RequestQueryProperty
        public void setHostId(String hostIdStr) {
            this.hostId = IdUtils.webIdStringToHostId(hostIdStr, true);
        }

        @Description("Идентификатор пользователя")
        @RequestQueryProperty(required = true)
        public void setUserId(long userId) {
            this.userId = userId;
        }
    }

    @Getter
    @AllArgsConstructor
    public static class Res implements ActionResponse.NormalResponse {
        private final Map<String, SimpleExperiment> experiments;
    }
}
