/**
 * Created by sam on 09.02.2015.
 */
import * as tslib_1 from "tslib";
import { behavior, mouse as d3mouse, select, selectAll } from 'd3';
import * as C from 'phovea_core/src/index';
import * as provenance from 'phovea_core/src/provenance';
import * as idtypes from 'phovea_core/src/idtype';
import { create as createAnnotation } from './annotation';
import * as cmode from './mode';
import * as dialogs from 'phovea_ui/src/dialogs';
import * as d3 from 'd3';
import * as vis from 'phovea_core/src/vis';
import * as utils from './utils';
import * as marked from 'marked';
import * as player from './player';
import * as $ from 'jquery';
import * as textPNG from './assets/text.png';
function to_duration(d) {
    var minutesSeconds = d3.time.format('%M:%S');
    return minutesSeconds(new Date(d));
}
function to_starting_time(d, story) {
    if (!d) {
        return d3.sum(story, function (d) { return d.duration + d.transition; });
    }
    var i = story.indexOf(d);
    return story.slice(0, i).reduce(function (a, b) { return a + b.duration + b.transition; }, d.transition);
}
var LevelOfDetail;
(function (LevelOfDetail) {
    LevelOfDetail[LevelOfDetail["None"] = 0] = "None";
    LevelOfDetail[LevelOfDetail["Small"] = 1] = "Small";
    LevelOfDetail[LevelOfDetail["Medium"] = 2] = "Medium";
    LevelOfDetail[LevelOfDetail["Large"] = 3] = "Large";
})(LevelOfDetail || (LevelOfDetail = {}));
function getLevelOfDetail() {
    var mode = cmode.getMode();
    if (mode.presentation >= 0.8) {
        return LevelOfDetail.Large;
    }
    if (mode.exploration > 0.3) {
        return LevelOfDetail.None;
    }
    if (mode.authoring >= 0.8) {
        return LevelOfDetail.Large;
    }
    return LevelOfDetail.Medium;
}
function isEditAble() {
    return getLevelOfDetail() >= LevelOfDetail.Large;
}
var VerticalStoryVis = (function (_super) {
    tslib_1.__extends(VerticalStoryVis, _super);
    function VerticalStoryVis(data, parent, options) {
        if (options === void 0) { options = {}; }
        var _this = _super.call(this) || this;
        _this.data = data;
        _this.parent = parent;
        _this.trigger = _this.update.bind(_this);
        _this.onSelectionChanged = function (event, slide, type, op, extras) {
            _this.$node.selectAll('div.story:not(.placeholder)').classed('phovea-select-' + type, function (d) {
                var isSelected = d === slide;
                if (isSelected && type === idtypes.defaultSelectionType) {
                    this.scrollIntoView();
                }
                return isSelected;
            });
            if (type === idtypes.defaultSelectionType) {
                _this.updateInfo(slide);
                _this.updateTimeIndicator(slide, extras.withTransition !== false);
            }
        };
        _this.onStateSelectionChanged = function (event, state, type, op, extras) {
            if (!state || extras.slideSelected === true) {
                return;
            }
            var slide = cmode.getMode().exploration < 0.8 ? _this.findSlideForState(state) : null;
            var selected = _this.data.selectedSlides(type);
            if ((slide && selected.indexOf(slide) >= 0) || (!slide && selected.length === 0)) {
                return;
            }
            if (type === idtypes.defaultSelectionType) {
                _this.data.selectSlide(slide, idtypes.SelectOperation.SET, idtypes.defaultSelectionType, { withTransition: false });
            }
            else {
                _this.data.selectSlide(slide, idtypes.SelectOperation.SET, type);
            }
        };
        _this.options = {
            scale: [1, 1],
            rotate: 0,
            class: 'vertical',
            xy: 'y',
            wh: 'height',
            topleft: 'top',
            thumbnails: true
        };
        _this.duration2pixel = d3.scale.linear().domain([0, 10000]).range([VerticalStoryVis.MIN_HEIGHT, 200]);
        _this.story = null;
        _this.player = null;
        _this.options = C.mixin(_this.options, options);
        if (_this.options.class === 'horizontal') {
            _this.options.xy = 'x';
            _this.options.wh = 'width';
            _this.options.topleft = 'left';
        }
        _this.$node = _this.build(d3.select(parent));
        C.onDOMNodeRemoved(_this.node, _this.destroy, _this);
        _this.player = new player.Player(data, _this.node.querySelector('#player_controls'));
        _this.bind();
        _this.story = _this.data.selectedSlides()[0] || _this.data.getSlideChains()[0];
        _this.update();
        return _this;
    }
    VerticalStoryVis.prototype.findSlideForState = function (state) {
        if (!this.story) {
            return null;
        }
        return C.search(provenance.toSlidePath(this.story), function (s) { return s.state === state; });
    };
    VerticalStoryVis.prototype.bind = function () {
        this.data.on('select_slide', this.onSelectionChanged);
        this.data.on('select_state', this.onStateSelectionChanged);
        this.data.on('start_slide,destroy_slide', this.trigger);
        cmode.on('modeChanged', this.trigger);
    };
    VerticalStoryVis.prototype.destroy = function () {
        _super.prototype.destroy.call(this);
        this.data.off('select_slide', this.onSelectionChanged);
        this.data.off('select_state', this.onStateSelectionChanged);
        this.data.off('start_slide,destroy_slide', this.trigger);
        cmode.off('modeChanged', this.trigger);
    };
    Object.defineProperty(VerticalStoryVis.prototype, "rawSize", {
        get: function () {
            return [300, 500];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(VerticalStoryVis.prototype, "node", {
        get: function () {
            return this.$node.node();
        },
        enumerable: true,
        configurable: true
    });
    VerticalStoryVis.prototype.option = function (name, val) {
        if (arguments.length === 1) {
            return this.options[name];
        }
        else {
            this.fire('option.' + name, val, this.options[name]);
            this.options[name] = val;
        }
    };
    VerticalStoryVis.prototype.locateImpl = function (range) {
        return Promise.resolve(null);
    };
    VerticalStoryVis.prototype.transform = function (scale, rotate) {
        if (rotate === void 0) { rotate = 0; }
        var bak = {
            scale: this.options.scale || [1, 1],
            rotate: this.options.rotate || 0
        };
        if (arguments.length === 0) {
            return bak;
        }
        var dims = this.data.dim;
        var width = 20, height = dims[0];
        this.$node.attr({
            width: width * scale[0],
            height: height * scale[1]
        }).style('transform', 'rotate(' + rotate + 'deg)');
        //this.$node.select('g').attr('transform', 'scale(' + scale[0] + ',' + scale[1] + ')');
        var act = { scale: scale, rotate: rotate };
        this.fire('transform', act, bak);
        this.options.scale = scale;
        this.options.rotate = rotate;
        return act;
    };
    VerticalStoryVis.prototype.switchTo = function (story) {
        if (story) {
            var storyStart = story;
            while (storyStart.previous) {
                storyStart = storyStart.previous;
            }
            this.story = storyStart;
            this.data.selectSlide(story);
        }
        else {
            this.story = null;
        }
        this.update();
    };
    VerticalStoryVis.prototype.build = function ($parent) {
        var $node = $parent.select('aside.provenance-story-vis');
        if ($node.empty()) {
            $node = $parent.append('aside').classed('provenance-story-vis', true);
        }
        $node.attr({
            'class': 'provenance-story-vis ' + this.options.class
        }).style('transform', 'rotate(' + this.options.rotate + 'deg)');
        $node.html("\n      <div>\n        <h2><i class=\"fa fa-video-camera\"></i> Story <span id=\"player_controls\">\n            <i data-player=\"backward\" class=\"btn btn-xs btn-default fa fa-step-backward\" title=\"Step Backward\"></i>\n            <i data-player=\"play\" class=\"btn btn-xs btn-default fa fa-play\" title=\"Play\"></i>\n            <i data-player=\"forward\" class=\"btn btn-xs btn-default fa fa-step-forward\" title=\"Step Forward\"></i>\n          </span>\n          <i class=\"fa fa-plus-circle\"></i></h2>\n        <form class=\"form-inline toolbar\" style=\"display: none\" onsubmit=\"return false;\">\n        <div class=\"btn-group btn-group-xs\" role=\"group\">\n          <button type=\"button\" class=\"btn btn-default dropdown-toggle\" data-toggle=\"dropdown\" aria-haspopup=\"true\"\n                  aria-expanded=\"false\">\n            Select<span class=\"caret\"></span>\n          </button>\n          <ul class=\"dropdown-menu\" id=\"story_list\">\n            <!--<li><a href=\"#\">A</a></li>-->\n          </ul>\n        </div>\n        <div class=\"btn-group btn-group-xs\" data-toggle=\"buttons\">\n          <button class=\"btn btn-default btn-xs\" data-create=\"plus\" title=\"create a new story\"><i class=\"fa fa-plus\"></i> New Story</button>\n          <button class=\"btn btn-default btn-xs\" data-create=\"clone\" title=\"create a new story by extracting the current path\"><i class=\"fa fa-files-o\"></i> Extract</button>\n          <button class=\"btn btn-default btn-xs\" data-create=\"bookmark\" title=\"create a new story by extracting all bookmarked ones\"><i class=\"fa fa-bookmark\"></i> Bookmarked</button>\n        </div>\n        </form>\n      </div>\n      <div class=\"current\">\n        <input type=\"text\" class=\"form-control\" placeholder=\"slide name\" disabled=\"disabled\">\n        <div class=\"name\"></div>\n        <textarea class=\"form-control\" placeholder=\"slide description\" disabled=\"disabled\"></textarea>\n        <div class=\"description\"></div>\n      </div>\n      <div class=\"stories " + this.options.class + "\">\n        <div class=\"line\"></div>\n        <div class=\"time_marker\"><i class=\"fa fa-circle\"></i></div>\n      </div>\n    ");
        var that = this;
        $node.selectAll('button[data-create]').on('click', function () {
            var create = this.dataset.create;
            var story;
            switch (create) {
                case 'plus':
                    story = that.data.startNewSlide('Welcome');
                    break;
                case 'clone':
                    var state = that.data.selectedStates()[0] || that.data.act;
                    story = that.data.startNewSlide('My story to ' + (state ? state.name : 'heaven'), state ? state.path : []);
                    break;
                case 'bookmark':
                    var states = that.data.states.filter(function (d) { return d.getAttr('starred', false); });
                    story = that.data.startNewSlide('My favorite findings', states);
                    break;
            }
            that.switchTo(story);
            return false;
        });
        var jp = $($node.node());
        jp.find('.dropdown-toggle').dropdown();
        jp.find('h2 i.fa-plus-circle').on('click', function () {
            jp.find('form.toolbar').toggle('fast');
        });
        {
            var $base_1 = $node.select('div.current');
            $base_1.select('input').on('change', function () {
                var d = that.data.selectedSlides()[0];
                if (d) {
                    d.name = this.value;
                }
                $base_1.select('div.name').html(marked(d.name));
                that.update();
            });
            $base_1.select('textarea').on('change', function () {
                var d = that.data.selectedSlides()[0];
                if (d) {
                    d.description = this.value;
                }
                $base_1.select('div.description').html(marked(d.description));
                //that.update();
            });
        }
        if (this.data.getSlideChains().length === 0) {
            jp.find('form.toolbar').toggle('fast');
        }
        return $node;
    };
    VerticalStoryVis.prototype.updateInfo = function (slide) {
        var $base = this.$node.select('div.current').datum(slide);
        $base.select('input').property('value', slide ? slide.name : '').attr('disabled', slide ? null : 'disabled');
        $base.select('div.name').html(slide ? marked(slide.name) : '');
        $base.select('textarea').property('value', slide ? slide.description : '').attr('disabled', slide ? null : 'disabled');
        $base.select('div.description').html(slide ? marked(slide.description) : '');
    };
    VerticalStoryVis.prototype.pushAnnotation = function (ann) {
        var selected = this.data.selectedSlides()[0];
        if (selected) {
            selected.pushAnnotation(ann);
        }
    };
    VerticalStoryVis.prototype.onSlideClick = function (d) {
        this.data.selectSlide(d, idtypes.SelectOperation.SET, idtypes.defaultSelectionType, { withTransition: false });
        if (d && d.state) {
            this.data.selectState(d.state, idtypes.SelectOperation.SET, idtypes.defaultSelectionType, { slideSelected: true });
        }
    };
    VerticalStoryVis.prototype.dndSupport = function (elem) {
        var that = this;
        elem
            .on('dragenter', function (d) {
            if (C.hasDnDType(d3.event, 'application/phovea-prov-state') || C.hasDnDType(d3.event, 'application/phovea-prov-story') || C.hasDnDType(d3.event, 'application/phovea-prov-story-text')) {
                d3.select(this).classed('hover', true);
                return false;
            }
        }).on('dragover', function (d) {
            if (C.hasDnDType(d3.event, 'application/phovea-prov-state') || C.hasDnDType(d3.event, 'application/phovea-prov-story') || C.hasDnDType(d3.event, 'application/phovea-prov-story-text')) {
                d3.event.preventDefault();
                C.updateDropEffect(d3.event);
                return false;
            }
        }).on('dragleave', function (d) {
            d3.select(this).classed('hover', false);
        }).on('drop', function (d) {
            d3.select(this).classed('hover', false);
            var e = d3.event;
            e.preventDefault();
            var fullStory = provenance.toSlidePath(that.story);
            var dStory = d.isPlaceholder ? d.to : d;
            var insertIntoStory = function (newSlide) {
                if (dStory == null) {
                    var bak = that.story;
                    that.story = newSlide;
                    if (bak) {
                        that.data.insertIntoSlide(newSlide, bak, true);
                    }
                }
                else {
                    that.data.insertIntoSlide(newSlide, dStory, false);
                }
                that.update();
            };
            if (C.hasDnDType(e, 'application/phovea-prov-state')) {
                var state = that.data.getStateById(parseInt(e.dataTransfer.getData('application/phovea-prov-state'), 10));
                insertIntoStory(that.data.wrapAsSlide(state));
            }
            else if (C.hasDnDType(e, 'application/application/phovea-prov-story-text')) {
                insertIntoStory(that.data.makeTextSlide());
            }
            else if (C.hasDnDType(e, 'application/phovea-prov-story')) {
                var story = that.data.getSlideById(parseInt(e.dataTransfer.getData('application/phovea-prov-story'), 10));
                if (fullStory.indexOf(story) >= 0 && e.dataTransfer.dropEffect !== 'copy') {
                    if (dStory == null) {
                        if (story !== that.story) {
                            var bak = that.story;
                            that.story = story;
                            that.data.moveSlide(story, bak, true);
                            that.update();
                        }
                    }
                    else {
                        var ref = dStory;
                        if (ref !== story) {
                            //we might moved the first one
                            if (story === that.story) {
                                that.story = story.next;
                            }
                            that.data.moveSlide(story, ref, false);
                            that.update();
                        }
                    }
                }
                else {
                    insertIntoStory(that.data.cloneSingleSlideNode(story));
                }
            }
            return false;
        });
    };
    VerticalStoryVis.prototype.changeDuration = function ($elem) {
        var that = this;
        $elem.call(d3.behavior.drag()
            .origin(function () { return ({ x: 0, y: 0 }); })
            .on('drag', function (d, i) {
            //update the height of the slide node
            var e = d3.event;
            var $elem = d3.select(this.parentElement);
            var height = Math.max(that.duration2pixel.range()[0], that.duration2pixel(d.duration) + e[that.options.xy]);
            $elem.style(that.options.wh, height + 'px');
            var change = that.duration2pixel.invert(height) - d.duration;
            var durations = that.$node.selectAll('div.story').filter(function (d) { return !d.isPlaceholder; });
            var stories = provenance.toSlidePath(that.story);
            durations.select('div.duration span').text(function (k) {
                var index = stories.indexOf(k);
                return to_duration(to_starting_time(k, stories) + (index > i ? change : 0));
            });
            that.$node.select('div.story.placeholder div.duration span').text(to_duration(to_starting_time(null, stories) + change));
        }).on('dragend', function (d) {
            //update the stored duration just once
            var h = parseInt(d3.select(this.parentElement).style(that.options.wh), 10);
            d.duration = that.duration2pixel.invert(h);
        }));
    };
    VerticalStoryVis.prototype.changeTransition = function ($elem) {
        var that = this;
        $elem.call(d3.behavior.drag()
            .origin(function () { return ({ x: 0, y: 0 }); })
            .on('drag', function (d, i) {
            //update the height of the slide node
            var e = d3.event;
            var $elem = d3.select(this.parentElement);
            var offset = Math.max(0, that.duration2pixel(d.transition) - VerticalStoryVis.MIN_HEIGHT + e[that.options.xy]);
            $elem.style('margin-' + that.options.topleft, offset + 'px');
            var change = that.duration2pixel.invert(offset + VerticalStoryVis.MIN_HEIGHT) - d.transition;
            var durations = that.$node.selectAll('div.story').filter(function (d) { return !d.isPlaceholder; });
            var stories = provenance.toSlidePath(that.story);
            durations.select('div.duration span').text(function (k) {
                var index = stories.indexOf(k);
                return to_duration(to_starting_time(k, stories) + (index >= i ? change : 0));
            });
            that.$node.select('div.story.placeholder div.duration span').text(to_duration(to_starting_time(null, stories) + change));
        }).on('dragend', function (d) {
            //update the stored duration just once
            var h = parseInt(d3.select(this.parentElement).style('margin-' + that.options.topleft), 10);
            d.transition = that.duration2pixel.invert(h + VerticalStoryVis.MIN_HEIGHT);
        }));
    };
    VerticalStoryVis.prototype.storyInteraction = function (elem) {
        var graph = this.data;
        elem.attr('draggable', true)
            .on('dragstart', function (d) {
            if (!isEditAble()) {
                d3.event.preventDefault();
                return;
            }
            var e = d3.event;
            e.dataTransfer.effectAllowed = 'copyMove'; //none, copy, copyLink, copyMove, link, linkMove, move, all
            e.dataTransfer.setData('text/plain', d.name);
            e.dataTransfer.setData('application/phovea-prov-story', String(d.id));
        })
            .on('click', this.onSlideClick.bind(this))
            .on('mouseenter', function (d) {
            if (d.state != null) {
                graph.selectState(d.state, idtypes.SelectOperation.SET, idtypes.hoverSelectionType);
            }
            graph.selectSlide(d, idtypes.SelectOperation.SET, idtypes.hoverSelectionType);
        })
            .on('mouseleave', function (d) {
            if (d.state != null) {
                graph.selectState(d.state, idtypes.SelectOperation.REMOVE, idtypes.hoverSelectionType);
            }
            graph.selectSlide(d, idtypes.SelectOperation.REMOVE, idtypes.hoverSelectionType);
        });
    };
    VerticalStoryVis.prototype.createToolbar = function ($elem) {
        var _this = this;
        var $toolbarEnter = $elem.append('div').classed('toolbar', true);
        $toolbarEnter.append('i').attr('class', 'fa fa-edit').on('click', function (d) {
            var e = d3.event;
            //remove me
            e.stopPropagation();
            e.preventDefault();
            dialogs.prompt(d.name, {
                title: 'Edit name',
                placeholder: 'Markdown supported...',
                multiline: true
            }).then(function (text) {
                d.name = text;
                _this.update();
                _this.updateInfo(d);
            });
            return false;
        });
        $toolbarEnter.append('i').attr('class', 'fa fa-copy').attr('title', 'clone slide').on('click', function (d) {
            var e = d3.event;
            //remove me
            e.stopPropagation();
            e.preventDefault();
            _this.data.moveSlide(_this.data.cloneSingleSlideNode(d), d, false);
            _this.update();
            return false;
        });
        /*$toolbar_enter.append('i').attr('class', 'fa fa-camera').attr('title','force update of preview').on('click', (d) => {
         //remove me
         d3.event.stopPropagation();
         d3.event.preventDefault();
         this.data.moveSlide(this.data.cloneSingleSlideNode(d), d, false);
         this.update();
         return false;
         });
         */
        $toolbarEnter.append('i').attr('class', 'fa fa-remove').attr('title', 'remove slide').on('click', function (d) {
            var e = d3.event;
            //remove me
            e.stopPropagation();
            e.preventDefault();
            if (d === _this.story) {
                _this.story = _this.story.next;
                if (_this.story === null) {
                    _this.data.removeFullSlide(d);
                    return;
                }
            }
            _this.data.removeSlideNode(d);
            _this.update();
        });
    };
    VerticalStoryVis.prototype.createLastPlaceholder = function ($p) {
        var that = this;
        $p.html("<div>\n       <button class=\"btn btn-default btn-xs\" data-add=\"text\" title=\"add text slide\"><i class=\"fa fa-file-text-o\"></i></button>\n       <button class=\"btn btn-default btn-xs\" data-add=\"extract\" title=\"add current state\"><i class=\"fa fa-file-o\"></i></button>\n       <button class=\"btn btn-default btn-xs\" data-add=\"extract_all\" title=\"add path to current state\"><i class=\"fa fa-files-o\"></i></button>\n       </div>\n       <div class=\"duration\"><span>00:00</span><i class=\"fa fa-circle\"></i></div>\n      ");
        $p.selectAll('button[data-add]').on('click', function () {
            var create = this.dataset.add;
            var path = provenance.toSlidePath(that.story);
            var last = path[path.length - 1];
            switch (create) {
                case 'text':
                    if (last) {
                        that.data.moveSlide(that.data.makeTextSlide('Unnamed'), last, false);
                    }
                    else {
                        that.story = that.data.startNewSlide('Welcome');
                    }
                    break;
                case 'extract':
                    var state = that.data.selectedStates()[0] || that.data.act;
                    var newSlide = that.data.extractSlide([state], false);
                    if (last) {
                        that.data.moveSlide(newSlide, last, false);
                    }
                    else {
                        that.story = newSlide;
                    }
                    break;
                case 'extract_all':
                    var state2 = that.data.selectedStates()[0] || that.data.act;
                    var newSlide2 = that.data.extractSlide(state2.path, false);
                    if (last) {
                        that.data.moveSlide(newSlide2, last, false);
                    }
                    else {
                        that.story = newSlide2;
                    }
                    break;
            }
            that.update();
        });
    };
    VerticalStoryVis.prototype.updateSelection = function () {
        var _this = this;
        var stories = this.data.getSlideChains();
        var $stories = this.$node.select('.dropdown-menu').selectAll('li').data(stories);
        $stories.enter().insert('li').append('a')
            .attr('href', '#').on('click', function (d) {
            _this.switchTo(d);
            d3.event.preventDefault();
        });
        $stories.select('a').text(function (d) { return d.name; });
        $stories.exit().remove();
    };
    VerticalStoryVis.prototype.update = function () {
        var _this = this;
        this.updateSelection();
        var storyRaw = provenance.toSlidePath(this.story);
        var story = storyRaw.length > 0 ? [{ id: 'f-1', i: -1, isPlaceholder: true, to: null }] : [];
        storyRaw.forEach(function (s, i) {
            story.push(s);
        });
        //duplicate the last placeholder
        story.push({
            id: 'l' + (storyRaw.length - 1),
            i: storyRaw.length - 1,
            isPlaceholder: true,
            to: storyRaw[storyRaw.length - 1],
            isLastPlaceholder: true
        });
        //this.$node.attr('width', (story.length * 70+4)*1.2);
        var toId = function (d) { return String(d.id); };
        var lod = getLevelOfDetail();
        this.$node
            .classed('large', lod === LevelOfDetail.Large)
            .classed('medium', lod === LevelOfDetail.Medium)
            .classed('small', lod === LevelOfDetail.Small);
        this.$node.select('div.stories')
            .classed('large', lod === LevelOfDetail.Large)
            .classed('medium', lod === LevelOfDetail.Medium)
            .classed('small', lod === LevelOfDetail.Small)
            .classed('no-thumbnails', !this.options.thumbnails);
        //var levelShift = [];
        //nodes.forEach((n: any) => levelShift[n.depth] = Math.min(levelShift[n.depth] || 10000, n.x));
        //nodes.forEach((n: any) => n.x -= levelShift[n.depth]);
        var $states = this.$node.select('div.stories').selectAll('div.story').data(story, toId);
        var $statesEnter = $states.enter().append('div').classed('story', true);
        var $storyEnter = $statesEnter.filter(function (d) { return !d.isPlaceholder; });
        var $placeholderEnter = $statesEnter.filter(function (d) { return d.isPlaceholder; }).classed('placeholder', true);
        $storyEnter.call(this.storyInteraction.bind(this));
        $storyEnter.append('div').classed('preview', true);
        $storyEnter.append('div').classed('slabel', true);
        $storyEnter.call(this.createToolbar.bind(this));
        $storyEnter.append('div').classed('duration', true).html('<span></span><i class="fa fa-circle"></i>');
        $storyEnter.append('div').classed('dragger', true)
            .call(this.changeDuration.bind(this))
            .call(this.dndSupport.bind(this));
        $storyEnter.append('div').classed('dragger-transition', true)
            .call(this.changeTransition.bind(this));
        $placeholderEnter.call(this.dndSupport.bind(this));
        {
            var p = $placeholderEnter.filter(function (d) { return d.isLastPlaceholder; });
            p.call(this.createLastPlaceholder.bind(this));
        }
        $states.order();
        var $stories = $states.filter(function (d) { return !d.isPlaceholder; });
        $stories.classed('text', function (d) { return d.isTextOnly; });
        $stories.attr('data-id', function (d) { return d.id; });
        $stories.attr('title', function (d) { return d.name + '\n' + (d.transition > 0 ? '(' + to_duration(d.transition) + ')' : '') + '(' + to_duration(d.duration) + ')'; });
        //$stories.attr('data-toggle', 'tooltip');
        $stories.select('div.preview').style('background-image', lod < LevelOfDetail.Medium || !this.options.thumbnails ? null : (function (d) { return d.isTextOnly ? "url(" + textPNG + ")" : "url(" + utils.thumbnail_url(_this.data, d.state) + ")"; }));
        $stories.select('div.slabel').html(function (d) { return d.name ? marked(d.name) : ''; });
        $stories.select('div.duration span').text(function (d, i) { return "" + to_duration(to_starting_time(d, storyRaw)); });
        $stories.style(this.options.wh, function (d) { return _this.duration2pixel(d.duration) + 'px'; });
        $stories.style('margin-' + this.options.topleft, function (d) { return _this.duration2pixel(d.transition) - VerticalStoryVis.MIN_HEIGHT + 'px'; });
        //const $placeholders = $states.filter((d) => d.isPlaceholder);
        $states.filter(function (d) { return d.isLastPlaceholder; }).select('div.duration span').text(to_duration(to_starting_time(null, storyRaw)));
        $states.exit().remove();
    };
    VerticalStoryVis.prototype.updateTimeIndicator = function (slide, withTransition) {
        var $marker = this.$node.select('div.time_marker');
        if (!slide) {
            $marker.style('display', 'none');
            return;
        }
        var bounds = C.bounds(this.$node.node().querySelector('div.story[data-id="' + slide.id + '"]'));
        var base = C.bounds(this.$node.node().querySelector('div.stories'));
        //console.log(bounds, base, bounds.y - base.y);
        var t = $marker
            .transition().ease('linear')
            .duration(slide.transition < 0 || !withTransition ? player.MIN_TRANSITION : slide.transition * player.FACTOR)
            .style('top', (bounds.y - base.y) + 'px');
        t.transition().ease('linear')
            .duration(slide.duration < 0 || !withTransition ? player.MIN_DURATION : slide.duration * player.FACTOR)
            .style('top', (bounds.y - base.y + bounds.h - 4) + 'px');
    };
    return VerticalStoryVis;
}(vis.AVisInstance));
export { VerticalStoryVis };
VerticalStoryVis.MIN_HEIGHT = 20;
export function create(data, parent, options) {
    if (options === void 0) { options = {}; }
    return new VerticalStoryVis(data, parent, options);
}
export function createStoryVis(graph, parent, main, options) {
    var r = createAnnotation(main, graph);
    var storyvis = create(graph, parent, {
        render: r.render,
        thumbnails: options.thumbnails
    });
    graph.on('select_slide_selected', function (event, state) {
        select('aside.annotations').style('display', state ? null : 'none');
    });
    select('aside.annotations > div:first-of-type').call(behavior.drag().on('drag', function () {
        var mouse = d3mouse(this.parentElement.parentElement);
        select(this.parentElement).style({
            left: mouse[0] + 'px',
            top: mouse[1] + 'px'
        });
    }));
    selectAll('aside.annotations button[data-ann]').on('click', function () {
        var create = this.dataset.ann;
        var ann;
        switch (create) {
            case 'text':
                ann = {
                    type: 'text',
                    pos: [10, 10],
                    text: ''
                };
                break;
            case 'arrow':
                ann = {
                    type: 'arrow',
                    pos: [10, 10],
                    at: [200, 200]
                };
                //that.data.appendToStory(that.story.story, that.data.makeTextStory('Unnamed');
                //this.actStory.addText();
                break;
            case 'frame':
                ann = {
                    type: 'frame',
                    pos: [10, 10],
                    size: [20, 20]
                };
                break;
        }
        if (storyvis && ann) {
            storyvis.pushAnnotation(ann);
        }
    });
    return storyvis;
}
//# sourceMappingURL=storyvis.js.map