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


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import ru.yandex.autotests.direct.db.beans.ads.internal.BannersInternalTemplateVariables;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.BannersInternalRecord;
import ru.yandex.autotests.direct.db.steps.base.BasePpcSteps;
import ru.yandex.qatools.allure.annotations.Step;

import static ru.yandex.autotests.direct.db.models.jooq.ppc.Tables.BANNERS_INTERNAL;

/**
 * Created by pashkus on 21/03/19.
 */
public class BannersInternalSteps extends BasePpcSteps {

    private static final Type TEMPLATE_VARIABLES_LIST_TYPE = new TypeToken<ArrayList<BannersInternalTemplateVariables>>() {
    }.getType();

    @Step("DB: добавление записи в таблицу ppc.banners_internal")
    public void addBannerInternal(BannersInternalRecord bannersInternal) {
        run(db -> db.insertInto(BANNERS_INTERNAL)
                .set(bannersInternal)
                .execute());
    }

    @Step("DB: обновление template_id в таблице ppc.banners_internal (bid: {0}, template_id: {1}")
    public void updateTemplateId(Long bid, Long templateId) {
        run(db -> db.update(BANNERS_INTERNAL)
                .set(BANNERS_INTERNAL.TEMPLATE_ID, templateId)
                .where(BANNERS_INTERNAL.BID.eq(bid))
                .execute());
    }

    @Step("DB: обновление template_variables в таблице ppc.banners_internal (bid: {0}, templabe_varibables: {1}")
    public void updateTemplateVaribables(Long bid, String templateVaiables) {
        run(db -> db.update(BANNERS_INTERNAL)
                .set(BANNERS_INTERNAL.TEMPLATE_VARIABLES, templateVaiables)
                .where(BANNERS_INTERNAL.BID.eq(bid))
                .execute());
    }

    @Step("DB: получение записи из таблицы ppc.banners_internal (bid:{0}")
    public BannersInternalRecord getBannersInternal(Long bid) {
        return exec(db -> db.selectFrom(BANNERS_INTERNAL)
                .where(BANNERS_INTERNAL.BID.eq(bid))
                .fetchOne());
    }

    @Nullable
    public List<BannersInternalTemplateVariables> getTemplateVariables(Long bid) {
        BannersInternalRecord bannersInternal = getBannersInternal(bid);
        return getTemplateVariables(bannersInternal);
    }

    @Nullable
    public static List<BannersInternalTemplateVariables> getTemplateVariables(BannersInternalRecord bannersInternal) {
        if (bannersInternal == null) {
            return null;
        }

        return new Gson().fromJson(bannersInternal.getTemplateVariables(), TEMPLATE_VARIABLES_LIST_TYPE);
    }
}
