import {IEmbeddedFileInput} from '../../interfaces/components/file-input/IEmbeddedFileInput';
import {IFileInputBus} from '../../interfaces/bus/IFileInputBus';

export class EmbeddedFileInput implements IEmbeddedFileInput {

    protected input:HTMLInputElement;

    protected browserBtn:HTMLElement;

    protected bus:IFileInputBus;

    protected onInput:(fileName:string)=>void;

    public setOnInput(callback:(fileName:string)=>void): void
    {
        this.onInput = callback;
    }

    public setValue(fileName:string): void
    {
        this.input.value = fileName;
    }

    public init(input:HTMLInputElement): void
    {
        this.input = input;
        let html = `
            <div class="input-group-append">
                <a href="#" class="input-group-text btn-info js-browser-btn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-file-earmark-arrow-down" viewBox="0 0 16 16">
                        <path d="M8.5 6.5a.5.5 0 0 0-1 0v3.793L6.354 9.146a.5.5 0 1 0-.708.708l2 2a.5.5 0 0 0 .708 0l2-2a.5.5 0 0 0-.708-.708L8.5 10.293V6.5z"/>
                        <path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z"/>
                    </svg>
                </a>
            </div>
        `;
        let div = document.createElement('div');
        div.innerHTML = html.trim();
        this.browserBtn = <HTMLElement>div.firstChild;
        this.input.classList.add('form-control');

        this.wrap(this.input, '<div class="input-group"></div>');
        this.input.parentElement.append(this.browserBtn);
    }

    private wrap(element:HTMLElement, wrapperHtml:string) {
        let div = document.createElement('div');
        div.innerHTML = wrapperHtml.trim();
        let wrapper = <HTMLElement>div.firstChild;
        element.parentNode.insertBefore(wrapper, element);
        wrapper.appendChild(element);
    }

    public setBus(bus:IFileInputBus)
    {
        this.bus = bus;
    }

    public eventsListen()
    {
        this.input.oninput = ()=>{
            if(this.onInput){
                this.onInput(<string>this.input.value);
            }
        };
        this.browserBtn.onclick = (e:Event)=>{
            e.preventDefault();
            this.bus.execBrowserModal()
                .then((fileName:string)=>{
                    this.input.value = fileName;
                    if(this.onInput){
                        this.onInput(fileName);
                    }
                });
        };
    }

}