package ru.yandex.webmaster3.internal.turbo;

import java.util.Map;

import lombok.Getter;
import lombok.Setter;
import lombok.Value;
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.WebmasterException;
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.turbo.model.TurboHostSettings;
import ru.yandex.webmaster3.core.turbo.model.desktop.TurboDesktopSettings;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.request.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.storage.abt.AbtService;
import ru.yandex.webmaster3.storage.turbo.service.settings.TurboSettingsService;

/**
 * Created by Oleg Bazdyrev on 09/01/2020.
 */
@ReadAction
@Description("Получение настроек Турбо для домена")
@Category("turbo")
@Component("/turbo/settings/get")
public class GetTurboSettingsAction extends InternalAction<GetTurboSettingsAction.Request, GetTurboSettingsAction.Response> {

    private final AbtService abtService;
    private final TurboSettingsService turboSettingsService;

    @Autowired
    public GetTurboSettingsAction(AbtService abtService, TurboSettingsService turboSettingsService) {
        super(InternalGrant.TURBO);
        this.abtService = abtService;
        this.turboSettingsService = turboSettingsService;
    }

    @Override
    public Response process(Request request) throws WebmasterException {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        TurboHostSettings settings = turboSettingsService.getSettings(domain);
        TurboDesktopSettings desktopSettings = turboSettingsService.getDesktopSettings(domain);
        Map<String, String> experiments = abtService.getUserExperiments(request.getUserId());
        experiments.putAll(abtService.getHostExperiments(request.getHostId()));
        return new Response(settings, desktopSettings, experiments);
    }

    @Getter
    @Setter(onMethod_ = @RequestQueryProperty)
    public static final class Request extends AbstractUserVerifiedHostRequest {
    }

    @Value
    public static final class Response implements ActionResponse.NormalResponse {
        TurboHostSettings settings;
        TurboDesktopSettings desktopSettings;
        Map<String, String> experiments;
    }
}
