package ru.yandex.webmaster3.storage.turbo.service.preview.app;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Value;

import ru.yandex.webmaster3.core.turbo.model.TurboHostSettings;
import ru.yandex.webmaster3.core.turbo.model.app.TurboAppSettings;
import ru.yandex.webmaster3.core.turbo.model.commerce.TurboCommerceSettings;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedSettings;
import ru.yandex.webmaster3.storage.turbo.dao.scc.TurboSccService;
import ru.yandex.webmaster3.storage.turbo.dao.scc.model.TurboSccPremoderationStatus;

/**
 * Created by Oleg Bazdyrev on 25/02/2019.
 */
@Value
public class TurboAppSettingsData {

    @JsonProperty("enabled")
    Boolean enabled;
    @JsonProperty("title")
    String title;
    @JsonProperty("reviews_show")
    Boolean reviewShow;
    @JsonProperty("reviews")
    TurboAppReviewsInfo reviewsInfo;
    @JsonProperty("categories")
    List<TurboSccPremoderationStatus.TurboPremodCategoryType> categories;

    public static TurboAppSettingsData fromAppSettings(TurboAppSettings appSettings,
                                                       TurboAppReviewsInfo reviewsInfo,
                                                       TurboHostSettings settings,
                                                       List<TurboFeedSettings> feeds) {
        if (appSettings == null) {
            return null;
        }

        Boolean appSettingsEnabled;
        TurboSccService.FrontModerationStatus status =
                TurboSccService.getFrontModerationStatus(settings, feeds);
        boolean isCartUrlEnabled = Optional.of(settings)
                .map(TurboHostSettings::getCommerceSettings)
                .map(TurboCommerceSettings::isCartUrlEnabled)
                .orElse(false);
        if (isCartUrlEnabled) {
            appSettingsEnabled = null;
        } else if (status == TurboSccService.FrontModerationStatus.FAILED || status == TurboSccService.FrontModerationStatus.BANNED) {
            appSettingsEnabled = false;
        } else if (status == TurboSccService.FrontModerationStatus.PASS) {
            appSettingsEnabled = true;
        } else {
            appSettingsEnabled = appSettings.getEnabled();
        }
        // https://st.yandex-team.ru/WMC-9648 5 пункт
        List<TurboSccPremoderationStatus.TurboPremodCategoryType> categories = Collections.emptyList();

        Boolean marketRatingShow = Optional.ofNullable(settings.getCommerceSettings())
                .map(TurboCommerceSettings::getMarketRatingShow)
                .orElse(Boolean.TRUE);
        return new TurboAppSettingsData(appSettingsEnabled, appSettings.getTitle(), marketRatingShow, reviewsInfo, categories);
    }
}
