import {IToolsPanel} from '../interfaces/components/IToolsPanel';
import {IAppBus} from '../interfaces/bus/IAppBus';
import {IAppCommands} from '../interfaces/commands/IAppCommands';
import * as types from '../types';

declare let settings:types.TSettings;

export class ToolsPanel implements IToolsPanel {

    protected container:HTMLElement;

    protected appBus:IAppBus;

    protected appCommands:IAppCommands;

    protected addDirButton:HTMLElement;

    protected addItemButton:HTMLElement;

    protected itemDropDown:HTMLElement;

    protected deleteButton:HTMLElement;

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

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

    public init(container:HTMLElement)
    {
        this.container = container;
        this.addDirButton = this.container.querySelector('.js-add-button');
        this.addItemButton = this.container.querySelector('.js-add-item-button');
        this.itemDropDown = this.container.querySelector('.js-items-dropdown');
        this.deleteButton = this.container.querySelector('.js-delete-button');
        this.eventsListen();
    }

    protected eventsListen()
    {
        this.addDirButton.onclick = ()=>{
            this.appBus.execDirModal()
                .then((name:string)=>{
                    return this.appCommands.newDir(settings.currentId, name);
                })
                .then((resp:any)=>{
                    if(resp.success){
                        this.appBus.newDir(resp.dir);
                    }
                });
        };
        this.addItemButton.onclick = ()=>{
            this.itemDropDown.classList.toggle('show');
        };
        this.itemDropDown.querySelectorAll('.js-dropdown-item').forEach((el:HTMLElement, index:number)=>{
            let type = el.getAttribute('item');
            el.onclick = ()=>{
                this.appBus.execItemModal()
                    .then((name:string)=>{
                        this.itemDropDown.classList.remove('show');
                        return this.appCommands.newItem(settings.currentId, type, name);
                    }, ()=>{
                        this.itemDropDown.classList.remove('show');
                    })
                    .then((resp:any)=>{
                        if(resp && resp.success){
                            this.appBus.newItem(resp.item);
                        }
                    });
            };
        });
    }

}