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

export class EmbeddedImageInput implements IEmbeddedFileInput {

    protected input:HTMLInputElement;

    protected browserBtn:HTMLElement;

    protected prevImg:HTMLElement;

    protected preloader:HTMLElement;

    protected bus:IFileInputBus;

    protected canvasContext:any;

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

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

    public setValue(fileName:string): void
    {
        this.input.value = fileName;
        this.previewImg(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);
        
        html = `
            <div class="prev-container">
                <canvas class="img-prev js-canvas"></canvas>
                <div class="preloader js-preloader">
                    <div class="lds-dual-ring"></div>
                </div>
            </div>
        `;
        div = document.createElement('div');
        div.innerHTML = html.trim();
        this.prevImg = <HTMLElement>div.firstChild;

        this.input.parentElement.parentElement.append(this.prevImg);
        this.preloader = this.input.parentElement.querySelector('.js-preloader');
        this.canvasContext = (<any>this.prevImg.querySelector('.js-canvas')).getContext('2d');
    }

    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()
    {
        let w = this.input.getAttribute('data-previwWidth') || this.input.parentElement.clientWidth;
        let ar = this.input.getAttribute('data-ar');
        this.prevImg.querySelector('.js-canvas').setAttribute('width', w.toString());
        if(ar){
            let h = +w / +ar;
            this.prevImg.querySelector('.js-canvas').setAttribute('height', h.toString());
        }else{
            this.prevImg.querySelector('.js-canvas').setAttribute('height', w.toString());
        }
        if(<string>this.input.value){
            this.previewImg(<string>this.input.value);
        }
        
        this.input.oninput = (e:Event)=>{
            let val = this.input.value;
            this.previewImg(val);
            if(this.onInput){
                this.onInput(val);
            }
        };
        this.browserBtn.onclick = (e:Event)=>{
            e.preventDefault();
            this.bus.execBrowserModal()
                .then((fileName:string)=>{
                    this.input.value = fileName;
                    this.previewImg(fileName);
                    if(this.onInput){
                        this.onInput(fileName);
                    }
                });
        };
    }

    protected previewImg(fileName:string)
    {
        let canvasWidth = this.prevImg.querySelector('.js-canvas').getAttribute('width');
        let canvasHeight = this.prevImg.querySelector('.js-canvas').getAttribute('height');
        let img = new Image();
        this.preloader.style.display = 'block';
        let ar = this.input.getAttribute('data-ar');
        let path = this.input.getAttribute('data-path');
        img.onload = ()=>{
            this.canvasContext.clearRect(0, 0, canvasWidth, canvasHeight);
            let imgH = img.height;
            let imgW = img.width;
            if(+ar == 0){
                this.canvasContext.drawImage(img, 0, 0, imgW, imgH, 0, 0, canvasWidth, canvasHeight);
                this.preloader.style.display = 'none';
                return;
            }
            let dx = 0; let dy = 0;
            if(+imgW / +imgH > +ar){
                // изображение вытянуто по ширине
                let scale = imgH / +canvasHeight;
                dx = (imgW - +canvasWidth * scale) / 2;
            }else{
                // изображение вытянуто по высоте
                let scale = imgW / +canvasWidth;
                dy = (imgH - +canvasHeight * scale) / 2;
            }
            this.canvasContext.drawImage(img, dx, dy, imgW - 2*dx, imgH - 2*dy, 0, 0, canvasWidth, canvasHeight);
            this.preloader.style.display = 'none';
        }
        img.src = path + fileName;
    }

}