define([
    '../../core/utils/data',
    '../../core/utils/helper',
    '../../core/utils/method',
    '../../core/models/index'
], (data, helper, method, model) => {
    (function($) {
        new method('tooltip', {
            init: function (element) {
                const context = this;

                const options = context.local._options;
                const direction = options.direction ? options.direction.toUpperCase() : 'LEFT';
                let promise = null;

                if (options.value === '') {
                    options.value = element.attr('title') || '';
                }

                element.addClass('works-tooltip-wrapper');

                const $tooltip = $(context.$helper.parseTemplate('tooltip', $.extend(options, {
                    direction: direction.toLowerCase()
                })));
                $tooltip.appendTo(element);

                context.$helper.bind(element, 'mouseover focus', function(event) {
                    $tooltip.addClass('anim-ready');

                    if(
                        direction === 'LEFT' ||
                        direction === 'RIGHT'
                    ) {
                        $tooltip.css({
                            top: (element.outerHeight() - $tooltip.outerHeight()) / 2,
                            bottom: 'auto'
                        });
                    }
                    else {
                        $tooltip.css({
                            left: (element.outerWidth() - $tooltip.outerWidth()) / 2,
                            right: 'auto'
                        });
                    }

                    context.$helper.invoke(promise);
                    promise = context.$helper.promise(() => {
                        $tooltip.addClass('anim-start');
                    }, 25);
                });

                context.$helper.bind(element, 'mouseout blur', event => {
                    $tooltip.removeClass('anim-start');
                    context.$helper.invoke(promise);
                    promise = context.$helper.promise(() => {
                        $tooltip.removeClass('anim-ready');
                    }, 25);
                });
            },
            template: {
                tooltip: '<div class="works-tooltip works-tooltip-{direction}">{value}<span class="works-tooltip-arrow"></span></div>'
            },
            options: {
                once: true,
                value: '',
                margin: 20,
                direction: 'left'
            }
        });
    }(jQuery));
});