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

import java.util.Map;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

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.user.service.UserHostsService;

/**
 * @author akhazhoyan 06/2018
 */
@ReadAction
@Category("abt")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public final class GetExperimentsAction extends Action<GetExperimentsAction.Request, GetExperimentsAction.Response> {

    private final AbtService abtService;
    private final UserHostsService userHostsService;

    @Override
    public Response process(Request 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));
        }
        return new Response(experiments);
    }

    public static class Request implements ActionRequest {
        private long userId;
        private WebmasterHostId hostId;

        public long getUserId() {
            return userId;
        }

        public WebmasterHostId getHostId() {
            return 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;
        }
    }

    public static class Response implements ActionResponse.NormalResponse {
        private final Map<String, String> experiments;

        public Response(Map<String, String> experiments) {
            this.experiments = experiments;
        }

        public Map<String, String> getExperiments() {
            return experiments;
        }
    }
}
