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

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

    private static id = 'custom-confirm-dialog';
    constructor() { }


    public presentConfirm(title: string, message: string, okLabel: string, onConfirm: any, onCancel?: any) {
        this.dismiss();
        document.body.appendChild(this.createDialog(title, message, okLabel));
        this.registerEvents(onConfirm, onCancel);
    }

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

    private registerEvents(onConfirm: any, onCancel?: any) {
        const okButton = document.getElementById('alert-dialog-ok');

        okButton.addEventListener('click', (e) => {
            if (onConfirm) {
                onConfirm();
            }
            e.stopImmediatePropagation();
        });

        const cancelButton = document.getElementById('alert-dialog-cancel');
        cancelButton.addEventListener('click', (e) => {

            if (onCancel) {
                onCancel();
            } else {
                this.dismiss();
            }
            e.stopImmediatePropagation();
        });

        const dialog = document.getElementById(AlertControllerService.id);
        dialog.addEventListener('click', (e) => {
            this.dismiss();
            e.stopImmediatePropagation();
        });
    }

    private innerTemplate(title: string, message: string, okLabel: string) {

        const template =
            // tslint:disable-next-line:quotemark
            "<div class='alert-dialog zoomIn' >" + " <p id='title' >" + title + "</p>" +
            // tslint:disable-next-line:quotemark
            " <p id='desc' >" + message + "</p>" + " <div class='buttons-area'>" +
            // tslint:disable-next-line:quotemark
            " <button id='alert-dialog-cancel' >" + "cancel" + "</button>" + " <button id='alert-dialog-ok' >" + okLabel
            // tslint:disable-next-line:quotemark
            + "</button>" + "</div> " + "</div>";

        return template;
    }

    private createDialog(title: string, message: string, okLabel: string) {
        const elemDiv = document.createElement('div');
        elemDiv.id = AlertControllerService.id;
        elemDiv.className = 'alert-dialog-page';
        elemDiv.innerHTML = this.innerTemplate(title, message, okLabel);
        return elemDiv;

    }

}

