package ru.yandex.canvas.model.elements;

import java.util.Map;

import javax.validation.Valid;

import ru.yandex.adv.direct.media.ElementOptions;
import ru.yandex.canvas.model.MediaSet;
import ru.yandex.canvas.model.MediaSetSubItem;
import ru.yandex.canvas.model.rtbhost.DimensionBuilder;
import ru.yandex.canvas.service.rtbhost.ConstructorData.ConstructorDataElement;

/**
 * @author oxid
 */
public class Video extends Element {

    @Valid
    private Options options;

    @Override
    public Options getOptions() {
        return options;
    }

    public void setOptions(Options options) {
        this.options = options;
    }

    @Override
    public ConstructorDataElement toRTBHostExportData(Map<String, MediaSet> mediaSets) {
        final MediaSet mediaSet = mediaSets.get(getMediaSet());

        String url = mediaSet != null ? mediaSet.getItems().stream()
                .flatMap(item -> item.getItems().stream())
                .map(MediaSetSubItem::getUrl)
                .findFirst().orElse(null) : null;  // take first URL of mediaSet present

        return new ConstructorDataElement(getType(), url, options.getWidth(), options.getHeight());
    }

    @Override
    public String toString() {
        return "Video{" +
                "options=" + options +
                '}';
    }

    public static final class Options extends Element.Options {
        private Integer width;
        private Integer height;

        public Integer getWidth() {
            return width;
        }

        public void setWidth(Integer width) {
            this.width = width;
        }

        public Integer getHeight() {
            return height;
        }

        public void setHeight(Integer height) {
            this.height = height;
        }

        @Override
        public String toString() {
            return "Options{" +
                    "width=" + width +
                    ", height=" + height +
                    '}';
        }

        @Override
        protected void fillProto(ElementOptions.Builder builder) {
            var size = DimensionBuilder.build(width, height);
            if (size != null) {
                builder.setSize(size);
            }
        }
    }
}
