'use strict';

pandora.ui.previewPlayer = function() {

    var $player,
        $list = pandora.$ui.list,
        item = Ox.last($list.options('selected')),
        playerRatio = pandora.site.video.previewRatio,
        size = getSize(playerRatio),
        ui = pandora.user.ui,
        options = {},
        that = Ox.Dialog({
                closeButton: true,
                content: Ox.Element(),
                fixedRatio: true,
                focus: false,
                height: size.height,
                maximizeButton: true,
                title: Ox._('Loading...'),
                width: size.width
            })
            .bindEvent({
                resize: function(data) {
                    // FIXME: why doesn't that.options('content') work here?
                    // (currently the only reason $image is in the outer scope)
                    $player && $player.options({
                        width: data.width,
                        height: data.height
                    });
                },
                pandora_find: function() {
                    that.close();
                },
                pandora_item: function() {
                    that.close();
                },
                pandora_page: function() {
                    that.close();
                },
                pandora_section: function() {
                    that.close();
                },
                close: function() {
                    $player.options({paused: true});
                },
            });

    function getSize(playerRatio) {
        var windowWidth = window.innerWidth * 0.8,
            windowHeight = window.innerHeight * 0.8,
            windowRatio = windowWidth / windowHeight;
        return {
            width: Math.round(playerRatio > windowRatio ? windowWidth : windowHeight * playerRatio),
            height: Math.round(playerRatio < windowRatio ? windowHeight : windowWidth / playerRatio)
        };
    }

    that.update = function() {
        pandora.requests.preview && pandora.api.cancel(pandora.requests.preview);
        pandora.requests.preview = pandora.api.find({
            keys: [
                'id', 'modified', 'playerRatio'
            ].concat(pandora.site.itemTitleKeys),
            query: {
                conditions: [{
                    key: 'id',
                    operator: '==',
                    value: Ox.last($list.options('selected'))
                }],
                operator: '&'
            }
        }, function(result) {
            var item = result.data.items[0],
                size = getSize(playerRatio),
                title = pandora.getItemTitle(item, true);
            pandora.api.get({id: item.id, keys: pandora.VIDEO_OPTIONS_KEYS}, function(result) {
                options = Ox.extend(
                    {item: item.id},
                    ui.videoPoints[item.id] || {},
                    options
                );
                if (!options.position) {
                    options.position = options['in'] || 0;
                }
                result.data.item = item.id
                let video = Ox.extend(result.data, pandora.getVideoOptions(result.data));
                if (!video.subtitles) {
                    video.subtitles = pandora.getSubtitles(video);
                }
                $player = Ox.VideoPlayer({
                        censored: video.censored,
                        censoredIcon: pandora.site.cantPlay.icon,
                        censoredTooltip: pandora.site.cantPlay.text,
                        controlsBottom: [
                            'play',
                            'volume',
                            'scale',
                            'timeline',
                            'position',
                            'settings'
                        ],
                        controlsTooltips: {
                            close: Ox._('Close'),
                            open: Ox._('Open {0}', [pandora.site.itemName.singular])
                        },
                        controlsTop: [
                            Ox.Fullscreen.available ? 'fullscreen' : 'space16',
                            'title',
                            'open'
                        ],
                        duration: video.duration,
                        enableFullscreen: Ox.Fullscreen.available,
                        enableKeyboard: true,
                        enableMouse: true,
                        enablePosition: true,
                        enableSubtitles: ui.videoSubtitles,
                        enableTimeline: true,
                        enableVolume: true,
                        height: size.height,
                        muted: ui.videoMuted,
                        paused: false,
                        loop: false,
                        playInToOut: false,
                        position: options.position,
                        resolution: ui.videoResolution,
                        scaleToFill: ui.videoScale == 'fill',
                        showIconOnLoad: true,
                        subtitles: video.subtitles,
                        subtitlesDefaultTrack: video.subtitlesDefaultTrack || Ox.getLanguageNameByCode(pandora.site.language),
                        subtitlesLayer: video.subtitlesLayer,
                        subtitlesOffset: ui.videoSubtitlesOffset,
                        subtitlesTrack: video.subtitlesTrack || Ox.getLanguageNameByCode(pandora.site.language),
                        timeline: pandora.getMediaURL('/' + options.item + '/' + 'timeline16p.png'),
                        timelineType: '',
                        timelineTypes: [],
                        title: video.title,
                        video: video.video,
                        volume: ui.videoVolume,
                        width: size.width
                    })
                    .bindEvent({
                        fullscreen: function(data) {
                            Ox.Fullscreen.toggle();
                        },
                        open: function() {
                            $player.options({paused: true});
                            var url = document.location.protocol + '//'
                                + document.location.hostname + '/'
                                + options.item + '/'
                                + Ox.formatDuration($player.options('position'));
                            pandora.openURL(url);
                        },
                        position: function(data) {
                            console.log('position', data)
                            pandora.UI.set(
                                'videoPoints.' + item.id + '.position',
                                data.position
                            );
                        },
                    });
                that.options({content: $player});

        });
        that.options({
                content: Ox.LoadingScreen().start(),
                title: title,
            })
            .setSize(size.width, size.height);
        });
        return that;
    }

    return that.update();

};
