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

import com.fasterxml.jackson.databind.JsonNode;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
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.data.WebmasterHostId;
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.TurboHostSettings.TurboHostSettingsBuilder;
import ru.yandex.webmaster3.core.turbo.model.TurboHostSettingsBlock;
import ru.yandex.webmaster3.core.turbo.model.desktop.TurboDesktopSettings.TurboDesktopSettingsBuilder;
import ru.yandex.webmaster3.core.turbo.model.desktop.TurboDesktopSettingsBlock;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.turbo.service.preview.TurboFeedPreviewService;
import ru.yandex.webmaster3.storage.turbo.service.preview.TurboHostSettingsUploadResponse;
import ru.yandex.webmaster3.storage.turbo.service.preview.TurboHostSettingsUploadResponse.SavedDocumentData;
import ru.yandex.webmaster3.storage.turbo.service.preview.TurboHostSettingsUploadResponse.SavedProductInfo;
import ru.yandex.webmaster3.storage.turbo.service.settings.SetTurboSettingsResponse;
import ru.yandex.webmaster3.storage.turbo.service.settings.TurboSettingsMergerService;
import ru.yandex.webmaster3.storage.turbo.service.settings.TurboSettingsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

/**
 * Created by Oleg Bazdyrev on 06/07/2017.
 */
@WriteAction
@Category("turbo")
@Description("Устанавливает настройки хоста для Турбо")
@AllArgsConstructor(onConstructor_ = @Autowired)
public class SetTurboSettingsAction extends AbstractUserVerifiedHostAction<SetTurboSettingsRequest, SetTurboSettingsResponse> {

    private TurboFeedPreviewService turboFeedPreviewService;
    private TurboSettingsMergerService turboSettingsMergerService;
    private TurboSettingsService turboSettingsService;

    @Override
    public SetTurboSettingsResponse process(SetTurboSettingsRequest request) {
        WebmasterHostId hostId = request.getHostId();
        String domain = WwwUtil.cutWWWAndM(hostId);
        TurboHostSettingsBuilder settingsBuilder = turboSettingsMergerService.mergeHostSettings(hostId, request.getUserId(),
                request.getSettings(), request.getSettingsBlocks(), true, null);
        TurboDesktopSettingsBuilder desktopSettingsBuilder = turboSettingsMergerService.mergeDesktopSettings(hostId, request.getUserId(),
                request.getDesktopSettings(), request.getDesktopSettingsBlocks(), true, null);

        if (request.getSettingsBlocks().contains(TurboHostSettingsBlock.ADVERTISING) ||
                request.getDesktopSettingsBlocks().contains(TurboDesktopSettingsBlock.ADVERTISING)) {
            turboSettingsService.sendNotificationsAboutImportantChanges(domain, request.getUserId(), settingsBuilder, desktopSettingsBuilder);
        }

        if (request.getSettingsBlocks().contains(TurboHostSettingsBlock.PAYMENTS)) {
            turboSettingsService.sendNotificationsAboutImportantCommerceChanges(domain, request.getUserId(), settingsBuilder);
        }

        // сразу отошлем настройки хоста
        TurboHostSettingsUploadResponse hostSettingsResponse = turboFeedPreviewService.uploadHostSettings(
                hostId, settingsBuilder.build(), desktopSettingsBuilder.build(), null, false);
        if (CollectionUtils.isEmpty(hostSettingsResponse.getSavedDocuments())) {
            throw new WebmasterException("Could not upload host newSettings",
                    new WebmasterErrorResponse.TurboErrorResponse(getClass(), null, "Could not upload host newSettings"));
        }
        // сохраним распаршенные значения для секций
        if (settingsBuilder.getCommerceSettings() != null) {
            JsonNode parsedAccordion = hostSettingsResponse.getSavedDocuments().get(0).getData().stream().findAny()
                    .map(SavedDocumentData::getProductInfo).map(SavedProductInfo::getAccordion).orElse(null);
            settingsBuilder.setCommerceSettings(settingsBuilder.getCommerceSettings().withParsedAccordion(parsedAccordion));
        }

        // сохраняем настройки
        if (!request.getSettingsBlocks().isEmpty()) {
            turboSettingsService.updateSettings(domain, settingsBuilder.build(), request.getUserId());
        }
        if (!request.getDesktopSettingsBlocks().isEmpty()) {
            turboSettingsService.updateDesktopSettings(domain, desktopSettingsBuilder.build(), request.getUserId());
        }

        return new SetTurboSettingsResponse.NormalResponse();
    }
}
