/*
 * Copyright (c) 2024 Huawei Device Co., Ltd. All rights reserved
 * Use of this source code is governed by a MIT license that can be
 * found in the LICENSE file.
 */

import {
  RNOHContext,
  RNViewBase,
  RNOHLogger,
} from '@rnoh/react-native-openharmony'
import { RNC } from './generated'

export const PROGRESS_VIEW_TYPE: string = RNC.RNCProgressView.NAME

@Component
export struct RNCProgressView {
  private logger!: RNOHLogger
  ctx!: RNOHContext
  tag: number = 0
  @State descriptorWrapper: RNC.RNCProgressView.DescriptorWrapper = {} as RNC.RNCProgressView.DescriptorWrapper;
  @State cleanUpCallbacks: (()=>void)[]=[]

  aboutToAppear() {
    this.logger = this.ctx!.logger.clone("RNCProgressView")
    this.onDescriptorWrapperChange(this.ctx.descriptorRegistry.findDescriptorWrapperByTag<RNC.RNCProgressView.DescriptorWrapper>(this.tag)!)
    this.cleanUpCallbacks.push(this.ctx.descriptorRegistry.subscribeToDescriptorChanges(this.tag,
      (descriptor) => {
        this.onDescriptorWrapperChange(new RNC.RNCProgressView.DescriptorWrapper(descriptor))
      }))
    this.logger.info(`[RNOH]: in RNCProgressView, ${JSON.stringify(this.descriptorWrapper.props)}`)
  }

  private onDescriptorWrapperChange(descriptorWrapper: RNC.RNCProgressView.DescriptorWrapper) {
    this.descriptorWrapper = descriptorWrapper
    this.logger.info(`[RNOH]: in descriptorWrapper, ${JSON.stringify(this.descriptorWrapper.props)}`)
  }

  aboutToDisappear() {
    this.cleanUpCallbacks.forEach(cb => cb())
  }

  roundToDecimal(num:number, decimalPlaces:number) {
  const factor = Math.pow(10, decimalPlaces);
  return Math.round(num * factor) / factor;
  }

  build() {
    RNViewBase({ ctx: this.ctx, tag: this.tag }) {
      if (this.descriptorWrapper.props.isIndeterminate) {
        Progress({ value: 0, type: ProgressType.Ring })
          .color(this.descriptorWrapper.props.progressTintColor.toRGBAString())
          .backgroundColor(this.descriptorWrapper.props.trackTintColor.toRGBAString())
          .style({ status: ProgressStatus.LOADING })
          .width("100%")
          .height("100%")
      } else {
        Progress({value: this.descriptorWrapper.props.progress ? this.roundToDecimal(this.descriptorWrapper.props.progress,2)*100 : 0,type: ProgressType.Linear})
          .color(this.descriptorWrapper.props.progressTintColor.toRGBAString())
          .backgroundColor(this.descriptorWrapper.props.trackTintColor.toRGBAString())
          .width("100%")
          .height("100%")
       }
    }
  }
}