package ru.yandex.autotests.direct.intapi.java.factories.creative;

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

import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesCreativeType;
import ru.yandex.autotests.direct.db.models.jooq.ppc.tables.records.PerfCreativesRecord;
import ru.yandex.autotests.direct.intapi.models.CreativeUploadData;
import ru.yandex.autotests.direct.intapi.models.ModerationInfo;
import ru.yandex.autotests.direct.intapi.models.ModerationInfoAspect;
import ru.yandex.autotests.direct.intapi.models.ModerationInfoHtml;
import ru.yandex.autotests.direct.intapi.models.ModerationInfoImage;
import ru.yandex.autotests.direct.intapi.models.ModerationInfoSound;
import ru.yandex.autotests.direct.intapi.models.ModerationInfoText;
import ru.yandex.autotests.direct.intapi.models.ModerationInfoVideo;
import ru.yandex.autotests.direct.intapi.models.YabsData;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;

public class CreativesFactory {
    public static final Integer DEFAULT_HEIGHT = 400;
    public static final Integer TOO_LONG_NAME_SIZE = 4096;
    public static final Integer DEFAULT_WIDTH = 300;
    public static final String DEFAULT_URL =
            "https://cdn-austrian.economicblogs.org/wp-content/uploads/2016/09/AdobeStock_58349892-300x300.jpeg";
    public final static Integer MAX_IMAGE_SIZE = 65535;
    public final static Integer MAX_CREATIVE_NAME_LENGTH = 255;

    public static List<CreativeUploadData> creativesWithSameIds() {
        CreativeUploadData creativeFirstData = defaultCreative();
        CreativeUploadData creativeSecondData = defaultCreative();
        creativeSecondData.setCreativeId(creativeFirstData.getCreativeId());
        return Arrays.asList(creativeFirstData, creativeSecondData);
    }

    public static CreativeUploadData defaultCreative() {
        return new CreativeUploadData()
                .withCreativeName("test_name")
                .withHeight(DEFAULT_HEIGHT)
                .withWidth(DEFAULT_WIDTH)
                .withCreativeType(CreativeUploadData.CreativeTypeEnum.IMAGE)
                .withModerationInfo(defaultModerationInfo())
                .withPreviewUrl(DEFAULT_URL)
                .withLivePreviewUrl(DEFAULT_URL)
                .withPresetId(1)
                .withIsAdaptive(false);
    }

    public static CreativeUploadData defaultVideoCreative() {
        return new CreativeUploadData()
                .withCreativeName("test_video_name")
                .withCreativeType(CreativeUploadData.CreativeTypeEnum.VIDEOADDITION)
                .withModerationInfo(defaultVideoModerationInfo())
                .withPreviewUrl(DEFAULT_URL)
                .withLivePreviewUrl(DEFAULT_URL)
                .withPresetId(2)
                .withIsAdaptive(false);
    }

    /*
    https://st.yandex-team.ru/CANVAS-953
    {
        "creative_id": 12345,
        "creative_name": "My fancy name",  # как пользователь ввел в нашем интерфейсе
        "creative_type": "html5",  # классификатор
        "width": 728,
        "height": 90,
        "preview_url": "https://avatars....",  # скриншот
        "live_preview_url": "https://storage.mds....",  # html-ка с обертками, рисующая креатив так, как он будет выглядеть на показе
        "archive_url": "https://storage....."  # zip-архив так, как его нам кинул пользователь,
        "yabs_data": {
            "html5": "true", # Флаг для ПК, чтобы использовать нашу секурную схему показа баннеров. true именно обернутое в кавычки, чтобы проскочить через валидации РТБ хоста
            "basePath": "https://storage..." # префикс до контента баннера, чтобы правильно работали относительные пути, который получен при складывании в MDS
        }
    }
     */
    public static CreativeUploadData defaultHtml5Creative() {
        return new CreativeUploadData()
                .withCreativeName("test_html5_name")
                .withCreativeType(CreativeUploadData.CreativeTypeEnum.HTML5)
                .withHeight(DEFAULT_HEIGHT)
                .withWidth(DEFAULT_WIDTH)
                .withPreviewUrl(DEFAULT_URL)
                .withLivePreviewUrl(DEFAULT_URL + "?live")
                .withArchiveUrl(DEFAULT_URL + ".zip")
                .withYabsData(new YabsData().withBasePath("http://ya.ru").withHtml5(true))
                .withPresetId(3)
                .withIsAdaptive(false);
    }

    public static ModerationInfo defaultVideoModerationInfo() {
        return new ModerationInfo()
                .withHtml(new ModerationInfoHtml().withUrl("https://storage.mds.yandex.net/"))
                .withVideos(Collections.singletonList(new ModerationInfoVideo()
                        .withStockId("stock:346457")
                        .withUrl("https://storage.mds.yandex.net"))
                ).withSounds(Collections.singletonList(new ModerationInfoSound()
                        .withStockId("stock:346457")
                        .withUrl("https://storage.mds.yandex.net"))
                ).withAspects(Collections.singletonList(new ModerationInfoAspect()
                        .withWidth(16L)
                        .withHeight(4L))
                );
    }

    public static ModerationInfo defaultModerationInfo() {
        return new ModerationInfo()
                .withHtml(new ModerationInfoHtml().withUrl("https://storage.mds.yandex.net/"))
                .withImages(Collections.singletonList(new ModerationInfoImage()
                        .withAlt("test")
                        .withUrl("https://storage.mds.yandex.net"))
                )
                .withTexts(Collections.singletonList(new ModerationInfoText()
                        .withColor("#FF00FF")
                        .withType("button")
                        .withText("test"))
                );
    }

    public static CreativeUploadData toCreativeUploadData(PerfCreativesRecord record) {
        CreativeUploadData result = new CreativeUploadData();
        result.setHeight(record.getHeight() == null ? null : record.getHeight().intValue());
        result.setWidth(record.getWidth() == null ? null : record.getWidth().intValue());
        result.setCreativeId(record.getCreativeId());
        result.setPreviewUrl(record.getPreviewUrl());
        result.setCreativeName(record.getName());
        result.setCreativeType(toCreativeTypeEnum(record.getCreativeType()));
        result.setModerationInfo(JsonUtils.getObject(record.getModerateInfo(), ModerationInfo.class));
        result.setStockCreativeId(record.getStockCreativeId());
        result.setLivePreviewUrl(record.getLivePreviewUrl());
        result.setArchiveUrl(record.getArchiveUrl());
        result.setYabsData(JsonUtils.getObject(record.getYabsData(), YabsData.class));
        result.setPresetId(record.getLayoutId().intValue());
        result.setIsAdaptive(record.getIsAdaptive() == 1 ? true : false);
        return result;
    }

    private static CreativeUploadData.CreativeTypeEnum toCreativeTypeEnum(PerfCreativesCreativeType creativeType) {
        if (PerfCreativesCreativeType.video_addition.equals(creativeType)) {
            return CreativeUploadData.CreativeTypeEnum.VIDEOADDITION;
        } else if (PerfCreativesCreativeType.html5_creative.equals(creativeType)) {
            return CreativeUploadData.CreativeTypeEnum.HTML5;
        } else {
            return CreativeUploadData.CreativeTypeEnum.IMAGE;
        }
    }
}
