import UI = Office.UI;
import AsyncResult = Office.AsyncResult;

var dialog: any

/**
 * 构建一个新的Dialog
 * @param {string} startAddress - 进入的地址
 * @param [Function] dialogHandler - 控制函数
 * @param [boolean] inFrame - 是否显示在iframe内
 * */
function dialogFactory(startAddress: string, dialogHandler?: (dialog: any, arg: any) => void, inFrame: boolean = false) {
  // 受制 需要检测是否包含路径url
  /** @todo 需要添加vue-router判断 */
  if (startAddress[0] === '/') {
    startAddress = `${window.location.origin}${startAddress}`
  }

  let ui: UI = Office.context.ui

  let callback: (result: AsyncResult) => void = dialogCallback(dialogHandler)

  ui.displayDialogAsync(startAddress, {height: 70, width: 70, displayInIframe: inFrame}, callback)
}

/**
 * dialog构建后的回调函数
 * 根据输入情况回调
 * */
function dialogCallback(dialogHandler?: Function): (result: AsyncResult) => void {

  return function (asyncResult: Office.AsyncResult) {
    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
      // switch (asyncResult.error.code) {
      //   case 12004:
      //     showNotification("Domain is not trusted");
      //     break;
      //   case 12005:
      //     showNotification("HTTPS is required");
      //     break;
      //   case 12007:
      //     showNotification("A dialog is already opened.");
      //     break;
      //   default:
      //     showNotification(asyncResult.error.message);
      //     break;
      // }
    }
    else {
      dialog = asyncResult.value;
      /*Messages are sent by developers programatically from the dialog using office.context.ui.messageParent(...)*/
      let messageHandler = messageHandlerFactory(dialogHandler)
      dialog.addEventHandler(Office.EventType.DialogMessageReceived, messageHandler)

      /*Events are sent by the platform in response to user actions or errors. For example, the dialog is closed via the 'x' button*/
      dialog.addEventHandler(Office.EventType.DialogEventReceived, eventHandler)
    }
  }
}

/**
 * 工厂函数
 * @param [Function] handler - 接收的函数
 * */
function messageHandlerFactory(handler?: Function) {
  return function (arg: string) {
    if (handler) handler(dialog, arg)
  }
}

function eventHandler(arg: any) {

  // // In addition to general system errors, there are 2 specific errors
  // // and one event that you can handle individually.
  // switch (arg.error) {
  //   case 12002:
  //     showNotification("Cannot load URL, no such page or bad URL syntax.");
  //     break;
  //   case 12003:
  //     showNotification("HTTPS is required.");
  //     break;
  //   case 12006:
  //     // The dialog was closed, typically because the user the pressed X button.
  //     showNotification("Dialog closed by user");
  //     break;
  //   default:
  //     showNotification("Undefined error in dialog window");
  //     break;
  // }
}

export default dialogFactory
