package ru.yandex.autotests.direct.db.steps;

import java.net.MalformedURLException;
import java.net.URL;

import ru.yandex.autotests.direct.db.models.jooq.ppcdict.enums.TrustedRedirectsRedirectType;
import ru.yandex.autotests.direct.db.models.jooq.ppcdict.tables.records.TrustedRedirectsRecord;
import ru.yandex.autotests.direct.db.steps.base.BasePpcDictSteps;
import ru.yandex.qatools.allure.annotations.Step;

import static ru.yandex.autotests.direct.db.models.jooq.ppcdict.tables.TrustedRedirects.TRUSTED_REDIRECTS;
/**
 * Created by ginger on 02.05.17.
 */
public class TrustedRedirectsSteps extends BasePpcDictSteps {
    public static final String HTTPS_ONLY = "https_only";
    public static final String ALLOW_WILDCARD = "allow_wildcard";

    @Step("DB: получение записи из ppcdict.trusted_redirects для domain = {0} c type = {1}")
    public TrustedRedirectsRecord getTrustedRedirectsRecord(String domain, TrustedRedirectsRedirectType type) {
        return exec(db ->
                db.selectFrom(TRUSTED_REDIRECTS)
                        .where(TRUSTED_REDIRECTS.DOMAIN.eq(domain).and(TRUSTED_REDIRECTS.REDIRECT_TYPE.eq(type)))
                        .fetchOne());
    }

    @Step("DB: добавление/обновление записи в ppcdict.trusted_redirects для id = {1}, type = {0}")
    public void saveTrustedRedirectsRecord(String url, TrustedRedirectsRedirectType type, String opts) {
        String domain = extractDomain(url);
        exec(db -> db.insertInto(TRUSTED_REDIRECTS, TRUSTED_REDIRECTS.DOMAIN, TRUSTED_REDIRECTS.REDIRECT_TYPE, TRUSTED_REDIRECTS.OPTS)
                .values(domain, type, opts)
                .onDuplicateKeyUpdate()
                .set(TRUSTED_REDIRECTS.OPTS, opts)
                .execute()
        );
    }

    @Step("DB: удаление записи в таблице ppcdict.trusted_redirects с domain: {0}")
    public void deleteRecord(String domain, TrustedRedirectsRedirectType type) {
        run(db -> db.deleteFrom(TRUSTED_REDIRECTS).where(TRUSTED_REDIRECTS.DOMAIN.eq(domain)
                .and(TRUSTED_REDIRECTS.REDIRECT_TYPE.eq(type))).execute());
    }

    private static String extractDomain(String url) {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
        try {
            return new URL(url).getHost();
        } catch (MalformedURLException ignore) {
            return url;
        }
    }
}
