import {
  IOverlayController,
  IDrawerOptions,
  IPopoverOptions,
  IModalOptions,
  IOverlayContainer,
  IOverlayPopoverContainer,
} from '@ibiz-template/runtime';
import { isFunction } from 'lodash-es';
import { createPopover } from '../app-popover/app-popover-component';
import { createModal } from '../app-modal/app-modal-component';
import { createDrawer } from '../app-drawer/app-drawer-component';

/**
 * 用不同呈现方式绘制组件的通用工具类
 *
 * @author lxm
 * @date 2022-11-08 16:11:09
 * @export
 * @class OverlayController
 * @implements {IOverlayController}
 */
export class OverlayController implements IOverlayController {
  popover<T = void>(
    element: HTMLElement,
    component: unknown,
    props?: IParams | undefined,
    opts?: IPopoverOptions | undefined,
  ): Promise<T> {
    const popover = this.createPopover(component, props, opts);
    popover.present(element);
    return popover.onWillDismiss();
  }

  createPopover(
    component: unknown,
    props?: IParams | undefined,
    opts?: IPopoverOptions | undefined,
  ): IOverlayPopoverContainer {
    return createPopover(
      isFunction(component)
        ? component
        : h => h(component as string, { props }),
      opts,
    );
  }

  drawer<T = void>(
    component: unknown,
    props?: IParams | undefined,
    opts?: IDrawerOptions | undefined,
  ): Promise<T> {
    const drawer = this.createDrawer(component, props, opts);
    drawer.present();
    return drawer.onWillDismiss();
  }

  createDrawer(
    component: unknown,
    props?: IParams | undefined,
    opts?: IDrawerOptions | undefined,
  ): IOverlayContainer {
    return createDrawer(
      isFunction(component)
        ? component
        : h => h(component as string, { props }),
      opts,
    );
  }

  async modal<T = void>(
    component: unknown,
    props?: IParams | undefined,
    opts?: IModalOptions | undefined,
  ): Promise<T> {
    const modal = this.createModal(component, props, opts);
    modal.present();
    return modal.onWillDismiss();
  }

  createModal(
    component: unknown,
    props?: IParams | undefined,
    opts?: IModalOptions | undefined,
  ): IOverlayContainer {
    return createModal(
      isFunction(component)
        ? component
        : h => h(component as string, { props }),
      opts,
    );
  }
}
