import ngModule from '../module';
import './zoom-image.scss';

export function directive($timeout) {
    let container;
    let keyDownHandler;

    function createContainers(src) {
        destroyContainers();

        container = document.createElement('div');
        container.className = 'vn-zoom-image';
        container.addEventListener('click', destroyContainers);

        let wrapper = document.createElement('div');
        container.appendChild(wrapper);

        let background = document.createElement('img');
        background.src = src;
        wrapper.appendChild(background);

        document.body.appendChild(container);
        keyDownHandler = e => onKeyDown(e);
        document.addEventListener('keydown', keyDownHandler);
    }

    function onKeyDown(event) {
        if (event.key === 'Escape')
            destroyContainers();
    }

    function destroyContainers() {
        if (!container) return;

        container.removeEventListener('click', destroyContainers);
        container.parentNode.removeChild(container);
        container = undefined;

        document.removeEventListener('keydown', keyDownHandler);
        keyDownHandler = undefined;
    }

    return {
        restrict: 'A',
        link: function($scope, $element, $attrs) {
            $element.on('click', function(event) {
                if (event.defaultPrevented) return;

                let src = $element[0].getAttribute('zoom-image') || $element[0].src;
                if (src)
                    createContainers(src);
                else
                    throw new Error('No image source detected');
            });
        }
    };
}
directive.$inject = ['$timeout'];

ngModule.directive('zoomImage', directive);