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

@Builder
function defaultBuilder(text: string) {
  Column() {
    LoadingProgress()
      .color($r('app.color.color_466afd'))
      .width(50)
      .height(50)

    Text(text)
      .fontColor($r('app.color.color_466afd'))
      .fontSize(12)
      .maxLines(1)
      .textOverflow({ overflow: TextOverflow.Ellipsis })
      .ellipsisMode(EllipsisMode.END)
      .margin({ left:10, top: 5, right: 10 })
      .width('auto')
      .height('auto')
  }
  .width(192)
  .height(124)
  .justifyContent(FlexAlign.Center)
  .borderRadius(6)
  .backgroundColor(Color.White)
  .padding({left: 10, right: 10})
}

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

  private static instance: MaterialLoadingDialog | null = null;

  static show(context: UIContext, text?: string) {
    if (MaterialLoadingDialog.instance === null) {
      MaterialLoadingDialog.instance = new MaterialLoadingDialog(context, text ? text : '');
    }
    MaterialLoadingDialog.instance?.openDialog();
  }

  static update(text: string) {
    MaterialLoadingDialog.instance?.updateDialog(text);
  }

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

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


  openDialog() {
    if (this.context !== null && this.contentNode !== null) {
      this.context.getPromptAction().openCustomDialog(this.contentNode, {
        onWillDismiss: () => {
          return 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.');
        })
    }
  }

  updateDialog(text: string) {
    this.contentNode?.update(text);
  }
}