package ru.yandex.webmaster3.viewer.http.metrika.crawl2;

import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.autodoc.common.doc.annotation.Description;
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.metrics.Category;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.metrika.MetrikaCrawlStateService;
import ru.yandex.webmaster3.storage.metrika.data.MetrikaCounterCrawlStateEnum;

/**
 * @author leonidrom
 */
@WriteAction
@Category("metrika")
@Description("Обновить настройки обхода по счетчикам метрики")
public class UpdateMetrikaCrawlSettingsAction extends Action<UpdateMetrikaCrawlSettingsRequest, UpdateMetrikaCrawlSettingsResponse> {
    private final MetrikaCrawlStateService metrikaCrawlStateService;

    @Autowired
    public UpdateMetrikaCrawlSettingsAction(MetrikaCrawlStateService metrikaCrawlStateService) {
        this.metrikaCrawlStateService = metrikaCrawlStateService;
    }

    @Override
    public UpdateMetrikaCrawlSettingsResponse process(UpdateMetrikaCrawlSettingsRequest request) throws WebmasterException {
        try {
            String domain = WwwUtil.cutWww(request.getHostId().getASCIIHostname());
            MetrikaCounterCrawlStateEnum newState = request.isEnabled()? MetrikaCounterCrawlStateEnum.ENABLED : MetrikaCounterCrawlStateEnum.DISABLED;
            metrikaCrawlStateService.updateCounterCrawlState(domain, request.getCounterId(), newState);

            return new UpdateMetrikaCrawlSettingsResponse.NormalResponse();
        } catch (WebmasterYdbException e) {
            throw e.asUnchecked();
        }
    }
}
