import Snap from 'snapsvg'
import Tooltip from '../Tooltip.vue'

var popoverOptions = {
    placement: 'auto',
    container: 'body',
    trigger: 'manual',
    html: true,
    title: '',
    content: '',
}

export default {
    methods: {
        addTooltip: function() {

            var vm = new Vue(Tooltip);

            if (this.originalAnnotation) {
                vm.originalTitle = this.originalAnnotation.title;
                vm.originalDescription = this.originalAnnotation.description;
                vm.originalTags = this.originalAnnotation.tags;
            }

            vm.$mount(jQuery('<div>').get(0));

            vm.$on('close', () => {
                this.clear();
            });
            vm.$on('save', (data) => {
                this.save(data);
            });

            popoverOptions.content = vm.$el;

            var target = new Snap(this.getTooltipTarget());

            var $el = $(target.node);

            $el.popover(popoverOptions);

            this.$on('drag:start', function() {
                $el.popover('hide');
            });
            this.$on('drag:end', function() {
                $el.popover('show');
            });

            $el.on('shown.bs.popover', (e) => {
                var $tip = $el.data('bs.popover').tip();
                $tip.find('input[name="title"]').focus();
                // Fixes tooltip positioning when page is scrolled
                // See https://github.com/twbs/bootstrap/issues/21855
                if (document.body.scrollTop > 0) {
                    $tip.css('top', parseInt($tip.css('top'), 10) + document.body.scrollTop);
                }
            });

            $el.popover('show');
        },
        destroyTooltip: function() {
            var target = new Snap(this.getTooltipTarget());

            var $el = $(target.node);
            if ($el.data('bs.popover')) {
                $el.popover('destroy');
            }
        },
        hideTooltip: function() {
            var target = new Snap(this.getTooltipTarget());

            var $el = $(target.node);
            if ($el.data('bs.popover')) {
                $el.popover('hide');
            }
        },
        showTooltip: function() {
            var target = new Snap(this.getTooltipTarget());

            var $el = $(target.node);
            if ($el.data('bs.popover')) {
                $el.popover('show');
            }
        },
    }
}
