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

import org.springframework.beans.factory.annotation.Required;
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.storage.crawl.UserCrawlSettings;
import ru.yandex.webmaster3.storage.crawl.service.CrawlSettingsService;
import ru.yandex.webmaster3.viewer.http.crawl.data.HostCrawlConstants;

/**
 * @author avhaliullin
 */
@WriteAction
@Category("crawl")
@Description("Сохранить настройки обхода для сайта")
public class UpdateCrawlSettingsAction extends Action<UpdateCrawlSettingsRequest, UpdateCrawlSettingsResponse> {
    private CrawlSettingsService crawlSettingsService;

    @Override
    public UpdateCrawlSettingsResponse process(UpdateCrawlSettingsRequest request) throws WebmasterException {
        double roundValue = round(request.getMultiplier());
        roundValue = Math.max(HostCrawlConstants.MULTIPLIER_MIN, roundValue);
        roundValue = Math.min(HostCrawlConstants.MULTIPLIER_MAX, roundValue);
        UserCrawlSettings newSettings = new UserCrawlSettings(request.isUseDefaults(), roundValue);
        crawlSettingsService.updateUserCrawlSettings(request.getHostId(), newSettings);
        return new UpdateCrawlSettingsResponse.NormalResponse(newSettings);
    }

    private double round(double rawValue) {
        return (double) Math.round(rawValue / HostCrawlConstants.MULTIPLIER_PRECISION) * HostCrawlConstants.MULTIPLIER_PRECISION;
    }

    @Required
    public void setCrawlSettingsService(CrawlSettingsService crawlSettingsService) {
        this.crawlSettingsService = crawlSettingsService;
    }
}
