/* eslint no-var: "error" */
/* eslint no-unused-vars: "off" */
/* eslint linebreak-style: "off" */
/* eslint promise/no-nesting: "off" */
/* eslint-env es6*/
/* eslint camelcase: "off" */
// Put this file in path/to/plugin/amd/src
// You can call it anything you like

import Debugger from './util/debugger';
import {get_strings} from 'core/str';
import {getStrings} from 'core/str';
import ModalFactory from 'core/modal_factory';
import ModalEvents from 'core/modal_events';

/* Determine the proper getstrings function to use (MDL4.3+ recommends use of getStrings, which is jquery independent) */
const getstrFunc = (getStrings !== undefined) ? getStrings : get_strings;

let debug = new Debugger("treestudyplan-actionhrefs");

 /**
  * Init function for tool-actionhrefs
  */
export function init() {
    getstrFunc([
        {key: 'ok', component: 'core'},
        {key: 'confirm', component: 'core'},
    ]).then((s) => {
        const strOk = s[0];
        const strConfirm = s[1];

        const els = document.querySelectorAll('a.m-action-confirm');
        els.forEach((el) => {
            el.addEventListener('click', (e) => {
                e.preventDefault();
                const link = e.currentTarget;
                let href = link.getAttribute('data-actionhref');
                let text = link.getAttribute('data-confirmtext');
                let oktext = link.getAttribute('data-confirmbtn');
                if (undefined == oktext) {
                    oktext = strOk;
                }
                let title = link.getAttribute('data-confirmtitle');
                if (undefined == title) {
                    title = strConfirm;
                }

                ModalFactory.create({
                    type: ModalFactory.types.SAVE_CANCEL,
                    title: title,
                    body: text,
                }).then((modal) => {
                    modal.setSaveButtonText(oktext);

                    let root = modal.getRoot();
                    root.on(ModalEvents.save, () => {
                        window.location = href;
                    });
                    modal.modal[0].style["max-width"] = "345px";
                    modal.show();
                    return modal;
                }).catch((x) => {
                    debug.warn(x);
                });
            });
        });
        return;
    }).catch((x) => {
        debug.warn(x);
    });
}
