package ru.yandex.webmaster3.viewer.http.turbo.host;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
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.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.TurboDisplaySettings;
import ru.yandex.webmaster3.core.turbo.model.TurboHostSettings;
import ru.yandex.webmaster3.core.turbo.model.TurboHostSettings.TurboHostSettingsBuilder;
import ru.yandex.webmaster3.core.turbo.model.desktop.TurboDesktopSettings;
import ru.yandex.webmaster3.core.turbo.model.desktop.TurboDesktopSettings.TurboDesktopSettingsBuilder;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.turbo.service.css.TurboCssErrorInfo;
import ru.yandex.webmaster3.storage.turbo.service.css.TurboCssValidatorResponse;
import ru.yandex.webmaster3.storage.turbo.service.preview.TurboFeedPreviewService;
import ru.yandex.webmaster3.storage.turbo.service.settings.TurboSettingsService;
import ru.yandex.webmaster3.storage.turbo.service.validation.TurboParserService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.viewer.http.turbo.host.SetTurboCssAction.Request;
import ru.yandex.webmaster3.viewer.http.turbo.host.SetTurboCssAction.Response;

/**
 * Created by Oleg Bazdyrev on 06/07/2017.
 */
@WriteAction
@Component("/turbo/settings/css/set")
@Category("turbo")
@Description("Устанавливает настройки css для хоста")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SetTurboCssAction extends AbstractUserVerifiedHostAction<Request, Response> {

    private final TurboSettingsService turboSettingsService;
    private final TurboParserService turboParserService;
    private final TurboFeedPreviewService turboFeedPreviewService;

    @Override
    public Response process(Request request) {
        try {
            WebmasterHostId hostId = request.getHostId();
            String domain = WwwUtil.cutWWWAndM(hostId);
            // старые настройки
            TurboCssValidatorResponse cssResponse = null;
            TurboHostSettings oldSettings = turboSettingsService.getSettings(domain);
            TurboDesktopSettings oldDesktopSettings = turboSettingsService.getDesktopSettings(domain);
            // common css
            if (!Objects.equals(oldSettings.getCss(), request.getCss())) {
                cssResponse = turboParserService.validateCss(request.getCss());
                if (TurboCssValidatorResponse.STATUS_SUCCESS.equals(cssResponse.getStatus())) {
                    TurboHostSettings newSettings = new TurboHostSettingsBuilder(oldSettings)
                            .setCss(request.getCss(), cssResponse.getResult())
                            .build();
                    turboSettingsService.updateSettings(domain, newSettings);
                    turboFeedPreviewService.uploadHostSettings(hostId, newSettings, oldDesktopSettings, null, false);
                }
            }
            // desktop css
            if (!Objects.equals(oldDesktopSettings.getCss(), request.getDesktopCss())) {
                cssResponse = turboParserService.validateCss(request.getDesktopCss());
                if (TurboCssValidatorResponse.STATUS_SUCCESS.equals(cssResponse.getStatus())) {
                    TurboDesktopSettings newDesktopSettings = new TurboDesktopSettingsBuilder(oldDesktopSettings)
                            .setCss(request.getDesktopCss())
                            .setMinifiedCss(cssResponse.getResult())
                            .build();
                    turboSettingsService.updateDesktopSettings(domain, newDesktopSettings);
                    turboFeedPreviewService.uploadHostSettings(hostId, oldSettings, newDesktopSettings, null, false);
                }
            }

            return new Response(cssResponse == null ? Collections.emptyList() : cssResponse.createErrorInfos());
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Error reading settings from Cassandra",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }

    @Getter
    @Setter(onMethod_ = @RequestQueryProperty)
    public static final class Request extends AbstractUserVerifiedHostRequest {
        @Description("Искомый css")
        private String css;
        @Description("css для десктопа")
        private String desktopCss;
    }

    @Value
    public static final class Response implements ActionResponse.NormalResponse {
        List<TurboCssErrorInfo> cssErrors;
    }

}
