import { IContextMenu } from '../interfaces/components/IContextMenu';
import { IAppBus } from '../interfaces/bus/IAppBus';
import { IAppCommands } from '../interfaces/commands/IAppCommands';
import { TDir } from '../types/TDir';

export class DirContextMenu implements IContextMenu {

    protected html: string = `
        <div class="context-menu">
            <div class="context-menu-item js-rename-button">
                Переименовать
            </div>
            <div class="context-menu-item js-delete-button">
                Удалить
            </div>
        </div>
    `;

    protected _template: HTMLElement;

    protected renameButton: HTMLElement;

    protected deleteButton: HTMLElement;

    protected appBus: IAppBus;

    protected appCommands: IAppCommands;

    protected dirData: TDir;

    public constructor() {
        let div = document.createElement('div');
        div.innerHTML = this.html.trim();
        this._template = <HTMLElement>div.firstChild;
        this.renameButton = this._template.querySelector('.js-rename-button');
        this.deleteButton = this._template.querySelector('.js-delete-button');
    }

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

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

    public setAppCommands(commands: IAppCommands) {
        this.appCommands = commands;
    }

    public eventsListen() {
        this.renameButton.onclick = () => {
            this.hide();
            setTimeout(() => {
                this.appBus.execDirModal(this.dirData.name)
                    .then((newName: string) => {
                        return this.appCommands.renameDir(this.dirData.id, newName);
                    })
                    .then((resp: any) => {
                        if (resp.success) {
                            this.appBus.renamedDir(resp.dir);
                        }
                    });
            }, 200);
        };
        this.deleteButton.onclick = () => {
            this.appCommands.deleteDir(this.dirData.id)
                .then((resp: any) => {
                    if (resp.success) {
                        this.appBus.deletedDir(this.dirData);
                    }
                });
        };
    }

    public show(x: number, y: number, dirData: TDir) {
        this.dirData = dirData;
        this._template.style.top = y.toString() + 'px';
        this._template.style.left = x.toString() + 'px';
        this._template.style.display = 'block';
    }

    public hide() {
        this._template.style.display = 'none';
    }

}