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

import java.util.EnumSet;
import java.util.Set;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
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.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.TurboHostSettings.TurboHostSettingsBuilder;
import ru.yandex.webmaster3.core.turbo.model.app.TurboAppSettings;
import ru.yandex.webmaster3.core.turbo.model.commerce.TurboCommerceSettingsBlock;
import ru.yandex.webmaster3.core.turbo.model.commerce.TurboNewCommerceSettings;
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.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;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

import static ru.yandex.webmaster3.viewer.http.turbo.commerce.SetTurboCommerceSettingsAction.Request;

/**
 * Created by Oleg Bazdyrev on 16/06/2020.
 */
@Slf4j
@Component("/turbo/ecommerce/settings/set")
@WriteAction
@Category("turbo")
@Description("Установка настроек нового е-коммерс")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SetTurboCommerceSettingsAction extends AbstractUserVerifiedHostAction<Request, SetTurboSettingsResponse> {

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

    @Override
    public SetTurboSettingsResponse process(Request request) {
        WebmasterHostId hostId = request.getHostId();
        String domain = WwwUtil.cutWWWAndM(hostId);
        var builder = turboSettingsMergerService.mergeCommerceSettings(hostId, request.getSettings(),
                request.getSettingsBlocks(), true);

        // сразу отошлем настройки хоста
        TurboAppSettings.TurboAppSettingsBuilder appSettingsBuilder = TurboAppSettings.builder();
        TurboHostSettingsBuilder settingsBuilder = new TurboHostSettingsBuilder(turboSettingsService.getSettings(domain));
        turboSettingsService.splitSettings(builder.build(), appSettingsBuilder, settingsBuilder);
        TurboHostSettingsUploadResponse hostSettingsResponse = turboFeedPreviewService.uploadHostSettings(
                hostId, settingsBuilder.build(), null, appSettingsBuilder.build(), 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(TurboHostSettingsUploadResponse.SavedDocumentData::getProductInfo)
                    .map(TurboHostSettingsUploadResponse.SavedProductInfo::getAccordion).orElse(null);
            settingsBuilder.setCommerceSettings(settingsBuilder.getCommerceSettings().withParsedAccordion(parsedAccordion));
        }

        // сохраняем настройки
        turboSettingsService.updateSettings(domain, appSettingsBuilder.build(), settingsBuilder.build());

        return new SetTurboSettingsResponse.NormalResponse();
    }

    @Getter
    @Setter(onMethod_ = @RequestQueryProperty)
    public static final class Request extends AbstractUserVerifiedHostRequest {
        @Description("Новые настройки нового е-коммерс")
        private TurboNewCommerceSettings settings;
        private Set<TurboCommerceSettingsBlock> settingsBlocks = EnumSet.noneOf(TurboCommerceSettingsBlock.class);
    }

}
