import { DisplayUtil } from '@pura/harmony-utils';
import { ImagePreview } from '@rv/image-preview';
import { TitleBar } from '../../view/TitleBar'
import { media } from '@kit.MediaKit';
import image from '@ohos.multimedia.image';
import { fileIo } from '@kit.CoreFileKit';

@Entry
@ComponentV2
struct PhotoViewPage {
  @Local title: string = ''
  @Local uri?: string = ''

  private imageSize: media.PixelMapParams = {}

  aboutToAppear(): void {
    this.initParams()
    this.initImageSize()
  }

  initParams() {
    const params = this.getUIContext().getRouter().getParams() as Record<string, Object>;
    if (params) {
      this.title = params.title as string
      this.uri = params.uri as string;
    }
  }

  initImageSize() {
    let file = fileIo.openSync(this.uri, fileIo.OpenMode.READ_ONLY)
    let imageSource = image.createImageSource(file.fd)
    let imageInfo = imageSource.getImageInfoSync()
    this.imageSize.width = imageInfo.size.width
    this.imageSize.height = imageInfo.size.height
  }

  build() {
    Column() {
      TitleBar({title: this.title}).width('100%')
      Stack() {
        ImagePreview() {
          Image(this.uri)
            .width('100%')
            .objectFit(ImageFit.Contain)
            .draggable(false)
            .sourceSize({
              width: px2vp(DisplayUtil.getWidth()),
              height: px2vp(Math.round(this.imageSize.height!! * DisplayUtil.getWidth() / this.imageSize.width!!))
            })
        }
      }
      .layoutWeight(1)
      .margin({bottom: 50})
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}