package ru.yandex.webmaster3.tanker;

import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.LocalDate;
import org.joda.time.format.ISODateTimeFormat;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.searchquery.QueryIndicator;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.TimeUtils;
import ru.yandex.webmaster3.core.util.URLEncodeUtil;
import ru.yandex.webmaster3.core.notification.UTMLabels;

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

/**
 * @author avhaliullin
 */
public class WebmasterLinksProvider {
    private final String baseUrl;
    private final UTMLabels utmLabels;

    public WebmasterLinksProvider(String baseUrl, UTMLabels utmLabels) {
        this.baseUrl = baseUrl;
        this.utmLabels = utmLabels;
    }

    private static String hostInPath(WebmasterHostId hostId) {
        return IdUtils.hostIdToWebIdString(hostId);
    }

    private String makeLink(String path, List<Pair<String, String>> params, Optional<String> fragmentOpt, String utmTerm) {
        StringBuilder result = new StringBuilder(baseUrl).append(path).append("?");
        params.forEach(param -> result.append(param.getKey()).append("=").append(URLEncodeUtil.urlEncode(param.getValue())).append("&"));
        result.append(String.format("utm_source=%s&utm_medium=%s&utm_campaign=%s&utm_content=%s&utm_term=%s",
                utmLabels.getSource(), utmLabels.getMedium(), utmLabels.getCampaign(), utmLabels.getContent(), utmTerm
        ));
        fragmentOpt.ifPresent(fragment -> result.append("#").append(fragment));
        return result.toString();
    }

    public String makeLinkToPost(String baseUrl, String path) {
        StringBuilder result = new StringBuilder(baseUrl).append(path).append("?");
        result.append(String.format("utm_source=%s&utm_medium=%s&utm_content=%s",
                utmLabels.getSource(), utmLabels.getMedium(), utmLabels.getContent()
        ));
        return result.toString();
    }

    public String achievementLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/quality-tools/quality/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String hostDashboard(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/dashboard/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String searchPages(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/indexing/searchable/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String checklistLink(WebmasterHostId hostId, String utmTerm, boolean problemsOnlyInTurbo, boolean problemsOnlyInTurboContent, String utmTermTurbo) {
        String section = "diagnosis";

        if (problemsOnlyInTurbo) {
            if (problemsOnlyInTurboContent) {
                section = "turbo";
            } else {
                section = "shop";
            }
        }

        String actualUtmTerm = problemsOnlyInTurbo ? utmTermTurbo : utmTerm;
        return makeLink(String.format("/site/%s/%s/checklist/", hostInPath(hostId), section), Collections.emptyList(), Optional.empty(), actualUtmTerm);
    }

    public String checklistOverallLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/diagnosis/checklist/overall/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String notificationSettings(String utmTerm) {
        return makeLink("/settings/", Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String hostNotificationSettings(String utmTerm) {
        return makeLink("/site/settings/host-notifications/", Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String hostNotificationSettings(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/settings/host-notifications/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String hostIndexingCrawlMetrika(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/indexing/crawl-metrika/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String hostMetrikaSettings(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/settings/metrika/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String supportLinkMetrika() {
        return "https://yandex.ru/support/webmaster/indexing-options/link-metrica.html";
    }

    public String supportLinkIKS() {
        return "https://yandex.ru/support/webmaster/site-quality-index.html";
    }

    public String importantUrls(WebmasterHostId hostId, boolean recommended, String utmTerm) {
        return makeLink(String.format("/site/%s/indexing/url-tracker/", hostInPath(hostId)), Collections.emptyList(),
                recommended ? Optional.of("recommended") : Optional.empty(), utmTerm);
    }

    public String iksLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/quality-tools/quality/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String improveIKSLink() {
        return "https://yandex.ru/dev/hubs/webmasters/?utm_source=webmaster&utm_medium=digest";
    }

    public String addSchema(String owner) {
        return "http://" + owner;
    }

    public String sitemapLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/indexing/sitemap/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String searchRecommendedLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/search/recommended/", hostInPath(hostId)), Collections.emptyList(), Optional.empty(), utmTerm);
    }

    public String turboYmlLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/shop/present/",hostInPath(hostId)), Collections.emptyList(), Optional.of("how-to-connect"), utmTerm);
    }

    public String reviewsLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/quality-tools/reviews/",hostInPath(hostId)), Collections.emptyList(), Optional.of("how-to-connect"), utmTerm);
    }

    public String digestCustomBlockLink1(){
        return "https://yandex.ru/dev/conversion/sitespeed/?utm_source=yandex.webmaster&utm_medium=digest&utm_campaign=sitespeed";
    }

    public String digestCustomBlockLink2(){
        return "https://yandex.ru/support/webmaster/site-content/goods-yml.html?utm_source=yandex.webmaster&utm_medium=digest&utm_campaign=serpsnippets";
    }

    public String digestCustomBlockLink3(){
        return "https://turboapps.yandex.ru/console/application/create";
    }

    public String queryGroupClickStats(WebmasterHostId hostId, LocalDate dateFrom, LocalDate dateTo, QueryIndicator orderBy, String utmTerm) {
        return makeLink(
                String.format("/site/%s/search/statistics/", hostInPath(hostId)),
                Arrays.asList(
                        Pair.of("deviceType", "ALL_DEVICES"),
                        Pair.of("indicator", "total-clicks-count"),
                        Pair.of("dateFrom", dateInQuery(dateFrom)),
                        Pair.of("dateTo", dateInQuery(dateTo)),
                        Pair.of("period", "DAY"),
                        Pair.of("orderBy", toLowerKebab(orderBy.name())),
                        Pair.of("orderDirection", "desc")
                ),
                Optional.empty(),
                utmTerm
        );
    }

    public String queriesClickStats(WebmasterHostId hostId, LocalDate dateFrom, LocalDate dateTo, String utmTerm) {
        return makeLink(
                String.format("/site/%s/search/statistics/", hostInPath(hostId)),
                Arrays.asList(
                        Pair.of("specialGroup", "TOP_3000_QUERIES"),
                        Pair.of("deviceType", "ALL_DEVICES"),
                        Pair.of("indicator", "total-clicks-count"),
                        Pair.of("dateFrom", dateInQuery(dateFrom)),
                        Pair.of("dateTo", dateInQuery(dateTo)),
                        Pair.of("period", "DAY"),
                        Pair.of("orderBy", "click-dynamics"),
                        Pair.of("orderDirection", "desc")
                ),
                Optional.empty(),
                utmTerm
        );
    }

    public String autoparserLink(WebmasterHostId hostId, String utmTerm) {
        return makeLink(String.format("/site/%s/turbo/sources/", hostInPath(hostId)), Collections.emptyList(), Optional.of("autoparser"), utmTerm);
    }

    public UTMLabels getUTMLabels() {
        return utmLabels;
    }

    private static String dateInQuery(LocalDate date) {
        return date.toDateTimeAtStartOfDay(TimeUtils.EUROPE_MOSCOW_ZONE).toString(ISODateTimeFormat.dateTimeNoMillis());
    }

    private static String toLowerKebab(String enumName) {
        return enumName.toLowerCase().replace('_', '-');
    }
}
