/*
 * Copyright (C) 2026 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import {
  CacheStrategy,
  ImageKnife,
  ImageKnifeComponent,
  ImageKnifeOption,
  BlurTransformation
} from '@ohos/libraryimageknife'
import { router } from '@kit.ArkUI';

@Entry
@Component
struct TestJpegPage {
  private dataArr: Array<string> = this.initData()
  private index: number = 0;
  @State private memoryUsage: number | undefined = 0;
  @State private imageWidth: number | undefined = 0;
  @State private imageHeight: number | undefined = 0;
  @State private transformationOn: boolean = false;
  @State private enableOptimize: boolean = false;
  @State private showPic: boolean = true;
  @State private pixelFormat: number = -1;
  @State private option: ImageKnifeOption = {
    loadSrc: "",
    border: {
      width: 1
    },
    objectFit: ImageFit.Cover,
    onLoadListener: {
      onLoadSuccess: (data) => {
        this.memoryUsage = ImageKnife.getInstance().getCurrentCacheSize(CacheStrategy.Memory)
        if (data) {
          (data as PixelMap)?.getImageInfo().then((res) => {
            this.pixelFormat = res.pixelFormat.valueOf();
          })
        }
      }
    },
    onComplete: (event) => {
      this.imageWidth = event?.width
      this.imageHeight = event?.height
    }
  }

  initData(): Array<string> {
    let arr: Array<string> = []
    let urlPrefix: string = "https://gitee.com/Keke_planet/test-demos/raw/master/docPic/"
    let types = ["big_jpeg/", "middle_jpeg/", "small_jpeg/"]

    types.forEach(jpegType => {
      for (let i = 1; i <= 9; i++) {
        arr.push(urlPrefix + jpegType + i + ".jpg")
      }
    });
    return arr;
  }

  aboutToAppear(): void {
    ImageKnife.getInstance().removeAllMemoryCache();
    this.option.loadSrc = this.dataArr[0];
  }

  aboutToDisappear(): void {
    ImageKnife.getInstance().setJpegOptimizeDecoding(false);
  }

  build() {
    Column() {
      Row() {
        Button("返回").onClick(() => {
          router.back()
        }).margin({ left: 10 })
      }.width("100%").justifyContent(FlexAlign.Start).margin({ top: 10 })

      Text(this.transformationOn ? "添加图形变换" : "未添加图形变换").margin({ top: 20 })
      Text(this.enableOptimize ? "已开启Jpeg解码优化" : "未开启Jpeg解码优化")
      if (this.memoryUsage === 0) {
        Text("图片加载中...")
      } else {
        Text("内存缓存使用量:" + this.memoryUsage)
      }

      Text(`图片宽:${this.imageWidth}; 图片高:${this.imageHeight};
       图片解码格式:${this.pixelFormat === 3 ? 'RGBA_8888' : this.pixelFormat === 9 ? 'NV12' : this.pixelFormat}`)
        .margin({ bottom: 10 })

      if (this.showPic) {
        ImageKnifeComponent({
          imageKnifeOption: this.option
        }).width(350).height(350)
      }

      Button("移除图形变换,重新加载").onClick(() => {
        if (this.option.transformation !== undefined) {
          ImageKnife.getInstance().removeAllMemoryCache();
          this.memoryUsage = 0;
          this.option.transformation = undefined
          this.transformationOn = false;
        }
      }).margin({ top: 10 })

      Button("添加图形变换,重新加载").onClick(() => {
        if (this.option.transformation == undefined) {
          ImageKnife.getInstance().removeAllMemoryCache();
          this.memoryUsage = 0;
          this.option.transformation = new BlurTransformation(5)
          this.transformationOn = true;
        }
      }).margin({ top: 10 })

      Button("更换图片").onClick(() => {
        ImageKnife.getInstance().removeAllMemoryCache();
        this.memoryUsage = 0;
        this.index++;
        if (this.index > this.dataArr.length - 1) {
          this.index = 0;
        }
        this.option.loadSrc = this.dataArr[this.index]
      }).margin({ top: 10 })

      Button(this.enableOptimize ? "关闭Jpeg解码优化" : "开启Jpeg解码优化").onClick(() => {
        this.enableOptimize = !this.enableOptimize;
        ImageKnife.getInstance().setJpegOptimizeDecoding(this.enableOptimize)
        ImageKnife.getInstance().removeAllMemoryCache()
        this.memoryUsage = 0;

        // 强制刷新,重新加载
        this.showPic = false;
        setTimeout(() => {
          this.showPic = true;
        }, 100)
      }).margin({ top: 10 })

      Button("切换填充样式").onClick(() => {
        if (this.option.objectFit === ImageFit.Cover) {
          this.option.objectFit = ImageFit.Contain;
        } else {
          this.option.objectFit = ImageFit.Cover;
        }
      }).margin({ top: 10 })
    }.width("100%").height("100%")
  }
}