import { ComponentContent } from '@kit.ArkUI';

@Builder
function defaultBuilder() {
  Column() {
    LoadingProgress()
      .color(Color.White)
      .width(50)
      .height(50)

    Text('加载中')
      .fontColor(Color.White)
      .fontSize(12)
      .margin({ top: 5 })
      .width('auto')
      .height('auto')
  }
  .justifyContent(FlexAlign.Center)
  .borderRadius(6)
  .backgroundColor('#CC000000')
  .width(86)
  .height(86)
}

export class LoadingDialog {
  context: UIContext | null = null;
  contentNode: ComponentContent<Object> | null = null;

  private static instance: LoadingDialog | null = null;

  static show(context: UIContext, cancelable: boolean = false) {
    if (LoadingDialog.instance === null) {
      LoadingDialog.instance = new LoadingDialog(context);
    }
    LoadingDialog.instance?.openDialog(cancelable);
  }

  static dismiss() {
    if (LoadingDialog.instance !== null) {
      LoadingDialog.instance.closeDialog();
      LoadingDialog.instance = null;
    }
  }

  constructor(context: UIContext) {
    this.context = context;
    this.contentNode = new ComponentContent(context, wrapBuilder(defaultBuilder));
  }

  openDialog(cancelable: boolean) {
    if (this.context !== null && this.contentNode !== null) {
      if (!cancelable) {
        this.context.getPromptAction().openCustomDialog(this.contentNode,  {
          onWillDismiss: () => {
            return false
          },
          autoCancel: false
        })
          .then(() => {
            console.info('OpenCustomDialog complete.');
          })
      } else {
        this.context.getPromptAction().openCustomDialog(this.contentNode, {
          autoCancel: false
        })
          .then(() => {
            console.info('OpenCustomDialog complete.');
          })
      }
    }
  }

  closeDialog() {
    if (this.context !== null && this.contentNode !== null) {
      this.context.getPromptAction().closeCustomDialog(this.contentNode)
        .then(() => {
          console.info('CloseCustomDialog complete.');
        })
    }
  }
}