package ru.yandex.canvas.service.rtbhost.helpers.creative;

import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import one.util.streamex.EntryStream;
import one.util.streamex.StreamEx;

import ru.yandex.canvas.model.CreativeData;
import ru.yandex.canvas.model.CreativeDocument;
import ru.yandex.canvas.model.MediaSet;
import ru.yandex.canvas.model.MediaSetItem;
import ru.yandex.canvas.model.MediaSetSubItem;
import ru.yandex.canvas.model.elements.Element;
import ru.yandex.canvas.model.elements.ElementType;
import ru.yandex.canvas.service.rtbhost.ConstructorData;
import ru.yandex.direct.bs.dspcreative.model.DspCreativeExportEntry;

public class GeoPinDspUploadHelper {
    /**
     * В ссылках на лого и изображение в конце пути orig подменяется на суффикс соответствующий типу элемента
     *
     * @param data
     */
    private CreativeData replaceGeoPinImageUrlSuffix(CreativeData data) {
        Map<String, String> typeToSuffix = Map.of(
                ElementType.IMAGE, "banner%s",
                ElementType.LOGO, "logo%s"
        );
        Map<String, String> mediaSetIdToSuffix = StreamEx.of(data.getElements())
                .filter(e -> typeToSuffix.containsKey(e.getType()))
                .mapToEntry(
                        Element::getMediaSet,
                        Element::getType
                )
                .mapValues(typeToSuffix::get)
                .toMap();
        data.setMediaSets(
                EntryStream.of(data.getMediaSets())
                        .mapToValue((id, mediaSet) -> replaceImageUrlSuffix(mediaSet, mediaSetIdToSuffix.get(id)))
                        .toMap()
        );

        return data;
    }

    /**
     * В ссылках внутри mediaSet в конце пути orig подменяется на указанный suffix
     *
     * @param mediaSet
     * @param suffix
     * @return
     */
    private static MediaSet replaceImageUrlSuffix(MediaSet mediaSet, String suffix) {
        if (suffix == null) {
            return mediaSet;
        }
        for (MediaSetItem item : mediaSet.getItems()) {
            for (MediaSetSubItem subItem : item.getItems()) {
                String url = subItem.getUrl();
                url = url.endsWith("orig") ? url.substring(0, url.lastIndexOf("orig")) + suffix : url;
                subItem.setUrl(url);
            }
        }
        return mediaSet;
    }

    public DspCreativeExportEntry toImportDSPCreativeEntry(CreativeDocument creativeDocument,
                                                           ObjectMapper objectMapper) {
        try {
            return DspCreativeExportEntry.builder()
                    .setDspId(1L)
                    .setCreativeId(creativeDocument.getId())
                    .setCreativeVersionId(creativeDocument.getId())
                    .setData("")
                    .setConstructorData(objectMapper.writeValueAsString(new ConstructorData(
                            replaceGeoPinImageUrlSuffix(creativeDocument.getData().onlyVisibleData()))))
                    .setStaticData(String.format("{\"creative_id\":\"%d\"}", creativeDocument.getId()))
                    .setEnabled(true)
                    .setStatic(false)
                    .setTag("yabs")
                    .setPostmoderated(true)
                    .setVideo(false)
                    .setAudio(false)
                    .setWidth(creativeDocument.getData().getWidth())
                    .setHeight(creativeDocument.getData().getHeight())
                    .setIsAdaptive(creativeDocument.getData().getOptions().getIsAdaptive())
                    .setIsGeoPin(true)
                    .build();

        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
