import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';

@Injectable({
    providedIn: 'root'
})
export class ProgressLoadingService {

    private static id = 'custom-progress-loader';
    private static idSmall = 'custom-progress-loader-small';
    private static isPresented = false;
    constructor(
        public platform: Platform
    ) { }


    public presentLoading(message: string) {
        // this.dismiss();
        if ( !ProgressLoadingService.isPresented ) {
            ProgressLoadingService.isPresented = true;
            document.body.appendChild( this.createLoader(message));
            this.disableEventsPropagation();
        }
    }

    private enableBackButton(enable: boolean ) {

        if ( enable ) {
            // take full controll 
            this.platform.backButton.subscribeWithPriority(1 , () => {
                alert('progress loading 0');
            });
        }
    }
    private disableEventsPropagation() {
        const view = document.getElementById( ProgressLoadingService.id);

        view.addEventListener('click', (e) => {
            e.stopImmediatePropagation();
        });
    }

    public dismiss() {
        ProgressLoadingService.isPresented = false;
        const element = document.getElementById( ProgressLoadingService.id );
        if (element) {
            element.remove();
        }
    }

    private innerTemplate(message: string) {

        const template =
            // tslint:disable-next-line:quotemark
            "<div class='container' > " +
            "<img class='loading-gif'  src='assets/icon/moving.gif' >"
            // " <p class='title' >" + message + "</p>" + "</div>";

        return template;
    }

    private createLoader(message: string) {
        const elemDiv = document.createElement('div');
        elemDiv.id = ProgressLoadingService.id;
        elemDiv.className = 'progress-loading-page';
        elemDiv.innerHTML = this.innerTemplate(message);
        return elemDiv;

    }



    private createLoaderSmall(message: string) {
        const elemDiv = document.createElement('div');
        elemDiv.id = ProgressLoadingService.idSmall;
        elemDiv.className = 'progress-loading-page-small';
        elemDiv.innerHTML = this.innerTemplateSmall(message);
        return elemDiv;

    }


    private innerTemplateSmall(message: string) {

        const template =
            // tslint:disable-next-line:quotemark
            "<img class='loading-gif'  src='assets/icon/progress-loading.gif' >" ;

        return template;
    }
}
