package ru.yandex.webmaster3.viewer.http.promo;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.host.service.HostOwnerService;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.host.service.CommercialOwnersService;
import ru.yandex.webmaster3.storage.services.MarketRatingInfo;
import ru.yandex.webmaster3.storage.services.ServiceInfo;
import ru.yandex.webmaster3.storage.services.SiteServiceType;
import ru.yandex.webmaster3.storage.services.SiteServicesCHDao;

/**
 * ishalaru
 * 22.04.2021
 **/
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class MarketPromoTeaserProvider implements AbstractHostTeaserProvider {
    private final CommercialOwnersService commercialOwnersService;
    private final SiteServicesCHDao mdbSiteServicesCHDao;
    private final HostOwnerService hostOwnerService;

    @Override
    public Collection<AbstractHostTeaser> createTeasers(WebmasterHostId hostId, Map<String, String> groupsByExperiments) {
        String owner = hostOwnerService.getHostOwner(WwwUtil.cutWWWAndM(hostId));
        if (commercialOwnersService.isCommercialOwner(IdUtils.urlToHostId(owner))) {
            String mascotOwner = hostOwnerService.getMascotHostOwner(hostId.getPunycodeHostname());
            final ServiceInfo serviceInfo = mdbSiteServicesCHDao.getSiteServiceInfo(mascotOwner).get(SiteServiceType.MARKET_RATING);
            if (serviceInfo == null || ((MarketRatingInfo) serviceInfo).getId() == 0) {
                if (hostId.hashCode() % 2 == 0) {
                    return List.of(new MarketPromoTeaser(HostTeaserType.MARKET_PROMO_TEASER, "MARKET_PROMO_BANNER_V1"));
                } else {
                    return List.of(new MarketPromoTeaser(HostTeaserType.MARKET_PROMO_TEASER, "MARKET_PROMO_BANNER_V2"));
                }
            }
        }
        return List.of();
    }
}
