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

import java.net.IDN;
import java.util.EnumMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Pattern;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Category;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.turbo.model.TurboLogo;
import ru.yandex.webmaster3.core.turbo.model.commerce.TurboColorScheme;
import ru.yandex.webmaster3.core.turbo.model.commerce.TurboNewCommerceSettings;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.turbo.dao.TurboDomainsStateCHDao;
import ru.yandex.webmaster3.storage.turbo.dao.TurboDomainsStateHelper;
import ru.yandex.webmaster3.storage.turbo.dao.logo.DefaultTurboLogoYDao;
import ru.yandex.webmaster3.storage.turbo.service.TurboDomainsStateService;
import ru.yandex.webmaster3.storage.turbo.service.preview.app.TurboAppReviewsInfo;
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.GetTurboCommerceSettingsAction.Request;
import static ru.yandex.webmaster3.viewer.http.turbo.commerce.GetTurboCommerceSettingsAction.Response;

/**
 * Created by Oleg Bazdyrev on 16/06/2020.
 */
@ReadAction
@Slf4j
@Component("/turbo/ecommerce/settings/get")
@Category("turbo")
@Description("Получить настройки Турбо-Екоммерс (ТурбоАппов) по домену")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetTurboCommerceSettingsAction extends AbstractUserVerifiedHostAction<Request, Response> {

    private static final Predicate<String> GOOD_PREFIX_PATTERN = Pattern.compile("[0-9a-zа-я]").asMatchPredicate();
    private static final String DEFAULT_PREFIX = "a"; //english a

    private final DefaultTurboLogoYDao defaultTurboLogoYDao;
    private final TurboSettingsService turboSettingsService;
    private final TurboDomainsStateCHDao turboDomainsStateCHDao;


    @Override
    public Response process(Request request) {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        TurboNewCommerceSettings commerceSettings = turboSettingsService.getNewCommerceSettings(domain);
        // дефолтгные логотипы
        String prefix = IDN.toUnicode(domain).substring(0, 1);
        if (!GOOD_PREFIX_PATTERN.test(prefix)) {
            prefix = DEFAULT_PREFIX;
        }
        Map<String, TurboLogo> logosForPrefix = defaultTurboLogoYDao.getLogosByColors(prefix);
        EnumMap<TurboColorScheme.Type, TurboLogo> defaultLogos = new EnumMap<>(TurboColorScheme.Type.class);
        logosForPrefix.forEach((color, logo) -> {
            defaultLogos.put(TurboColorScheme.Type.valueOf(color.toUpperCase()), logo);
        });
        final TurboDomainsStateService.TurboDomainState domainState = turboDomainsStateCHDao.getDomainState(domain, TurboDomainsStateHelper.getAppReviewFields());
        return new Response(commerceSettings, defaultLogos,
                MarketReviewInfo.create(domain, Optional.ofNullable(domainState.getAppReviewsInfo()).orElse(TurboAppReviewsInfo.empty(domain))));
    }

    public static final class Request extends AbstractUserVerifiedHostRequest {

    }

    @Value
    public static final class Response implements ActionResponse.NormalResponse {
        @Description("Новые настройки e-commerce")
        TurboNewCommerceSettings settings;
        @Description("Все варианты дефолтных логотипов (для разных цветовых тем)")
        Map<TurboColorScheme.Type, TurboLogo> defaultLogos;
        @Description("Информацию о рейтинге маркета")
        MarketReviewInfo marketReviewInfo;

    }

    @Value
    private static class MarketReviewInfo {
        @JsonProperty("rating")
        Double rating;
        @JsonProperty("link")
        String link;
        @JsonProperty("count")
        Long count;

        public static MarketReviewInfo create(String domain, TurboAppReviewsInfo turboAppReviewsInfo) {
            return new MarketReviewInfo(turboAppReviewsInfo.getRating(), Optional.ofNullable(turboAppReviewsInfo.getLink()).orElse(TurboAppReviewsInfo.defaultLink(domain)), turboAppReviewsInfo.getCount());
        }
    }
}
