import { IItem } from '../interfaces/components/IItem';
import { IAppBus } from '../interfaces/bus/IAppBus';
import * as types from '../types';

declare let settings: types.TSettings;

export class Item implements IItem {

    protected html: string = `
        <div class="dir">
            <div class="item-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" fill="currentColor" class="bi bi-file-earmark" viewBox="0 0 16 16">
                    <path d="M14 4.5V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h5.5L14 4.5zm-3 0A1.5 1.5 0 0 1 9.5 3V1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4.5h-2z"/>
                </svg>
            </div>
            <div class="item-name js-name"></div>
            <div class="tooltiptext js-full-name"></div>
        </div>
    `;

    protected _template: HTMLElement;

    protected name: HTMLElement;

    protected fullName: HTMLElement;

    protected appBus: IAppBus;

    protected data: types.TItem;

    public constructor() {
        let div = document.createElement('div');
        div.innerHTML = this.html.trim();
        this._template = <HTMLElement>div.firstChild;
        this.name = this._template.querySelector('.js-name');
        this.fullName = this._template.querySelector('.js-full-name');
    }

    public get template(): HTMLElement {
        return this._template;
    }

    public get id(): string {
        return this.data.id;
    }

    public setAppBus(bus: IAppBus) {
        this.appBus = bus;
    }

    public eventsListen() {
        let options = {
            title: this.data.name,
        };
        this.makeTooltip(this.name, options);

        this._template.onclick = () => {
            window.location.href = settings.itemUrl + '?item-id=' + this.data.id;
        };
        this._template.oncontextmenu = (e: Event) => {
            e.preventDefault();
            this.appBus.execItemContextMenu((<any>e).pageX, (<any>e).pageY, this.data);
        };
    }

    private makeTooltip(el: HTMLElement, options: any): void {
        const tooltipText = <HTMLElement>(el.nextElementSibling);
        tooltipText.innerText = options.title;
        el.addEventListener('mouseover', () => {
            tooltipText.style.visibility = 'visible';
            tooltipText.style.opacity = '1';
        });

        el.addEventListener('mouseout', () => {
            tooltipText.style.visibility = 'hidden';
            tooltipText.style.opacity = '0';
        });
    }

    public load(data: types.TItem) {
        this.data = data;
        this.name.innerText = data.name;
        this.fullName.innerText = data.name;
    }

    public rename(name: string) {
        this.name.innerText = name;
    }

    public createSelf(): Item {
        return new Item();
    }

}