import { BridgePlugin } from '../bridge';
import { get } from 'para-utils';
import { INtvCallbackResult, INtvCallback } from '../../types/INtvDtoProtocol';

export enum DisplayType {
  Icon = 'icon',
  Text = 'text',
}

export interface ILeft {
  left?: { tagName?: string; type?: DisplayType.Icon, value?: string };
  right?: { tagName?: string; type: DisplayType.Text, value: string };
  // 禁止默认的back能力
  forbidBack?: 'true' | 'false';
}

export interface ICenter {
  left?: { tagName?: string; type: DisplayType.Text, value: string };
  right?: { tagName?: string; type: DisplayType.Icon, value: string };
}

export interface IRight {
  left?: { tagName?: string; type: DisplayType.Icon, value: string };
  right?: { tagName?: string; type: DisplayType, value: string };
}

export interface INavbarResult {
  [index: string]: any;
}

export interface INavbarParam {
  left?: ILeft;
  center?: ICenter;
  right?: IRight;
  // 标题栏是否悬浮, 放到URL参数里面, 因为在webview初始化时就要指定，所以不放在参数里指定

  // 透明度 0:全透明, 255:不透明, // 0 - 255,如果指定了ntv_bar_float自动先变成全透明
  opacity?: string; // '0 到 255';
  // 状态栏，'true'标识白色的状态栏文字，默认'false',显示黑色文字
  isStatusBarWhiteColor?: 'true' | 'false';
  // #ea4155 注意Native,只能是#666666 不能是#666
  bgColor?: string;
  // #18188c 注意Native,只能是#666666 不能是#666
  fontColor?: string;
}

export class SetNavbar<K> extends BridgePlugin<INavbarParam, K>{
  protected get ntvPluginName() {
    return '_ntv_navbar_set_navbar';
  }

  protected get availableMinVersion() {
    return '1.0.0';
  }

  protected bridgeExecChrome(pluginName?: string | undefined): void {
    // 可针对不同运行环境实现特定的调用逻辑来MOCK，弥补平台差异性.
    // throw new Error('bridgeExecChrome() 未针对当前环境实现');
    console.warn('当前浏览器环境:bridgeExecChrome()');
    if (this.param) {
      document.title = get(this.param, 'center.left.value', '');
    } else {
      throw new Error('请指定HEADER BAR 的标准参数，浏览器环境只支持title');
    }
  }
}

/**
 * 配置webview 头部，包括左侧，右侧，中间，以及回调函数，注意，此函数应尽量避免多次重复调用, 因为每次调用会生成一个实例
 * 每一次调用webview都会生成一个唯一的callback签名函数，理论上native除了ajax请求代理会开多个回调的栈记录
 * 一般都是只保留最后一次调用的回调签名函数，会造成前面绑定的回调函数内存浪费. 或者直接使用返回 SetNavbar类实例，自行管理如: setFloatNavbar()方法
 * @param param 设置WEBVIEW 配置参数
 * @returns Promise<INavbarResult>
 */
export const setNavbar = (param: INavbarParam, callback?: INtvCallback<INavbarResult>) => {
  // delay,强制等待10毫秒，等native bridge准备就绪
  setTimeout(() => {
    return new SetNavbar<INavbarResult>(param).invokeBind(callback);
  }, 10);
}

/**
 * 返回NavBar的实例，一般用于设置悬浮标题栏
 * @param param 默认参数
 * @returns SetNavbar<INavbarParam, INavbarResult>
 */
export const setFloatNavbar = (param: INavbarParam) => {
  return new SetNavbar<INavbarResult>(param);
};

/**
 * 如果单纯设置webview标题，则调用此方法去设置.
 * @param title 设置WEBVIEW 标题
 * @returns void
 */
export const setPageTitle = (title: string) => {
  const center: ICenter = { left: { type: DisplayType.Text, value: title } };
  setTimeout(() => {
    new SetNavbar<void>({ center }).invoke();
  }, 10);
};