'use strict';

const DialogType = require('./DialogType-2114c337.js');
const index = require('./index-1be40f19.js');

// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
let getRandomValues;
const rnds8 = new Uint8Array(16);
function rng() {
  // lazy load so that environments that need to polyfill have a chance to do so
  if (!getRandomValues) {
    // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
    getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);

    if (!getRandomValues) {
      throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
    }
  }

  return getRandomValues(rnds8);
}

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */

const byteToHex = [];

for (let i = 0; i < 256; ++i) {
  byteToHex.push((i + 0x100).toString(16).slice(1));
}

function unsafeStringify(arr, offset = 0) {
  // Note: Be careful editing this code!  It's been tuned for performance
  // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
}

const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
const native = {
  randomUUID
};

function v4(options, buf, offset) {
  if (native.randomUUID && !buf && !options) {
    return native.randomUUID();
  }

  options = options || {};
  const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`

  rnds[6] = rnds[6] & 0x0f | 0x40;
  rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided

  if (buf) {
    offset = offset || 0;

    for (let i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }

    return buf;
  }

  return unsafeStringify(rnds);
}

class ApplicationUtils {
  static async getDefaultMessageOptions() {
    if (!this.i18n) {
      this.i18n = await index.initI18n();
    }
    return {
      canClose: true,
      labelCancel: this.i18n("app.no"),
      labelConfirm: this.i18n("app.yes"),
      btnConfirmDanger: false
    };
  }
  static async showDialog(title, message, icon = null, confirm, dialogType = DialogType.DialogType.DEFAULT, options) {
    if (options) {
      const defaultMessageOptions = await this.getDefaultMessageOptions();
      options = Object.assign(Object.assign({}, defaultMessageOptions), options);
    }
    return new Promise(resolve => {
      let dialog = document.createElement("ez-dialog");
      window.document.body.appendChild(dialog);
      dialog.show(title, message, dialogType, confirm, icon, options.labelCancel, options.labelConfirm, options.btnConfirmDanger, options.beforeClose)
        .then(ok => {
        dialog.remove();
        return resolve(ok);
      });
    });
  }
  static async alert(title, message, icon = null, options) {
    if (!options) {
      const defaultMessageOptions = await this.getDefaultMessageOptions();
      options = defaultMessageOptions;
    }
    return ApplicationUtils.showDialog(title, message, icon, false, DialogType.DialogType.WARN, options);
  }
  static async error(title, message, icon = null, options) {
    if (!options) {
      const defaultMessageOptions = await this.getDefaultMessageOptions();
      options = defaultMessageOptions;
    }
    return ApplicationUtils.showDialog(title, message, icon, false, DialogType.DialogType.CRITICAL, options);
  }
  static async success(title, message, icon = null, options) {
    if (!options) {
      const defaultMessageOptions = await this.getDefaultMessageOptions();
      options = defaultMessageOptions;
    }
    return ApplicationUtils.showDialog(title, message, icon, false, DialogType.DialogType.SUCCESS, options);
  }
  static async confirm(title, message, icon = null, dialogType = DialogType.DialogType.WARN, options) {
    if (!options) {
      const defaultMessageOptions = await this.getDefaultMessageOptions();
      options = defaultMessageOptions;
    }
    return ApplicationUtils.showDialog(title, message, icon, true, dialogType, options);
  }
  static async message(title, message, icon = null, options) {
    if (!options) {
      const defaultMessageOptions = await this.getDefaultMessageOptions();
      options = defaultMessageOptions;
    }
    return ApplicationUtils.showDialog(title, message, icon, false, DialogType.DialogType.DEFAULT, options);
  }
  static async info(message, options) {
    const defaultMessageOptions = await this.getDefaultMessageOptions();
    if (options !== defaultMessageOptions) {
      options = Object.assign(Object.assign({}, defaultMessageOptions), options);
    }
    let useIcon = false;
    let toast = document.querySelector("ez-toast");
    if (!toast) {
      toast = document.createElement("ez-toast");
      const icon = document.createElement("ez-icon");
      icon.className = "ez-margin-right--small";
      icon.slot = "icon";
      icon.style.setProperty("--ez-icon--color", "var(--color--success)");
      toast.appendChild(icon);
      window.document.body.appendChild(toast);
    }
    if (options.iconName) {
      const iconElem = toast.querySelector("ez-icon");
      if (iconElem) {
        iconElem.iconName = options.iconName;
        useIcon = true;
      }
    }
    else {
      useIcon = false;
    }
    toast.show(message, 5000, useIcon, options.canClose);
  }
  static isModalContent(content) {
    return content instanceof HTMLElement && content.tagName === 'EZ-MODAL-CONTAINER';
  }
  /**
   * Exibe um popup configurado com os parâmetros informados e retorna um callBack
   * para removêlo da DOM quando necessário.
   *
   * @param popupProps
   */
  static async showPopup(popupProps) {
    var _a, _b;
    const popup = document.createElement("ez-popup");
    window.document.body.appendChild(popup);
    const { content } = popupProps;
    popup.setAttribute('id', v4());
    popup.heightMode = (_a = popupProps.size) !== null && _a !== void 0 ? _a : "auto";
    popup.opened = true;
    if (ApplicationUtils.isModalContent(content)) {
      popup.appendChild(content);
      popup.useHeader = false;
    }
    else {
      popup.ezTitle = (_b = popupProps.title) !== null && _b !== void 0 ? _b : "";
      popup.innerHTML = content;
    }
    return () => popup.remove();
  }
  static async showModal(modalProps) {
    modalProps = Object.assign(Object.assign({}, ApplicationUtils.defaultModalProps), modalProps);
    const modal = document.createElement("ez-modal");
    window.document.body.appendChild(modal);
    modal.setAttribute('id', v4());
    modal.modalSize = modalProps.size;
    modal.align = modalProps.position;
    modal.heightMode = modalProps.heightMode;
    modal.closeEsc = modalProps.closeEsc;
    modal.closeOutsideClick = modalProps.closeOutsideClick;
    modal.scrim = modalProps.useScrimLight ? 'light' : 'medium';
    if (modalProps.content instanceof String || typeof modalProps.content === 'string') {
      modal.innerHTML = modalProps.content;
    }
    else {
      modal.appendChild(modalProps.content);
    }
    modal.opened = true;
    return () => modal.remove();
  }
  static showAlerts(props) {
    const alertListId = 'EzAlertList';
    let alertList = document.getElementById(alertListId);
    if (!alertList) {
      alertList = document.createElement('ez-alert-list');
      alertList.setAttribute("id", alertListId);
      window.document.body.appendChild(alertList);
    }
    props = Object.assign(Object.assign({}, ApplicationUtils.defaultAlertListProps), props);
    alertList.itemRightSlotBuilder = props.itemRightSlotBuilder;
    alertList.enableDragAndDrop = props.enableDragAndDrop;
    alertList.enableExpand = props.enableExpand;
    alertList.opened = props.opened;
    alertList.alerts = props.alerts;
  }
}
ApplicationUtils.defaultModalProps = {
  content: null,
  position: 'right',
  size: 'small',
  heightMode: 'regular',
  closeOutsideClick: true,
  closeEsc: true
};
ApplicationUtils.defaultAlertListProps = {
  alerts: [],
  enableDragAndDrop: true,
  enableExpand: true,
  itemRightSlotBuilder: null,
  opened: true
};

exports.ApplicationUtils = ApplicationUtils;
