import { LoadingView } from './LoadingView'
import { ComponentContent, PromptAction } from '@kit.ArkUI'

export class Loading {
  static uiContext?: UIContext
  static promptAction?: PromptAction
  static componentContent?: ComponentContent<LoadingBuilderOptions>

  static init(uiContext: UIContext) {
    if (!Loading.uiContext) {
      Loading.uiContext = uiContext
      Loading.promptAction = Loading.uiContext.getPromptAction();
      Loading.componentContent = new ComponentContent(Loading.uiContext, wrapBuilder(loadingBuilder));
    }
  }

  static async showLoading(options: LoadingBuilderOptions | string = {}) {
    if (Loading.uiContext) {
      let loadingProps = options
      if (typeof options === 'string') {
        loadingProps = { text: options }
      }
      const opt = loadingProps as LoadingBuilderOptions
      Loading.componentContent?.update(opt)

      try {
        await Loading.promptAction?.openCustomDialog(Loading.componentContent, {
          autoCancel: opt.autoCancel == true,
          transition: TransitionEffect.IDENTITY,
          maskColor: Color.Transparent
        })
      } catch (error) {
        // Dialog显示异常
      }
    }
  }

  static async hideLoading() {
    Loading.promptAction?.closeCustomDialog(Loading.componentContent).catch(() => {
      // Dialog隐藏异常
    })
  }
}

@Builder
function loadingBuilder(options: LoadingBuilderOptions = {}) {
  LoadingView({
    loadingTips: options?.text || '加载中...'
  })
}


export interface LoadingBuilderOptions {
  text?: string,
  autoCancel?: boolean
}
