/*
 * Copyright (C) 2024 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 { ImageKnifeComponent,BlurTransformation } from '@ohos/libraryimageknife';
import fs from '@ohos.file.fs';
import image from '@ohos.multimedia.image';
import { common2D, drawing } from '@kit.ArkGraphics2D';
import { PageViewModel } from './model/PageViewModel';
import { mapData, MAP_DATA_KEYS } from "./model/ImageUrlData"
@Entry
@Component
struct SingleImage {
  resource: string = 'app.media.svgSample'
  scroller: Scroller = new Scroller;
  localFile: string = getContext(this).filesDir + '/icon.png'
  @State pixelMap:PixelMap | undefined = undefined;
  @State DrawingColorFilter: ColorFilter | undefined = undefined
  private color: common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 };
  aboutToAppear(): void {
    // 拷贝本地文件
    let icon: Uint8Array = getContext(this).resourceManager.getMediaContentSync($r('app.media.startIcon'));
    let file = fs.openSync(this.localFile, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
    fs.writeSync(file.fd, icon.buffer);
    fs.fsyncSync(file.fd);
    fs.closeSync(file);
    this.changePic(getContext().resourceManager.getMediaContentSync( $r('app.media.aaa'))
      .buffer as ArrayBuffer);


  }

  build() {
    Scroll(this.scroller) {
      Column() {
        Text($r('app.string.Local_SVG'))
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
        ImageKnifeComponent({
          imageKnifeOption: {
            loadSrc: $r(this.resource),
            placeholderSrc: $r('app.media.loading'),
            errorholderSrc: $r('app.media.failed'),
            objectFit: ImageFit.Contain
          }
        }).width(100).height(100)
          .onClick(()=>{
            this.DrawingColorFilter = drawing.ColorFilter.createBlendModeColorFilter(this.color, drawing.BlendMode.SRC_IN);
          })
        ImageKnifeComponent({
          imageKnifeOption: {
            loadSrc: $r('[sharedlibrary].media.pngSample'),
            placeholderSrc: $r('app.media.loading'),
            errorholderSrc: $r('app.media.failed'),
            objectFit: ImageFit.Contain
          }
        }).width(100).height(100)
        Text($r('app.string.Under_context_file'))
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
        ImageKnifeComponent({
          imageKnifeOption: {
            loadSrc: this.localFile,
            placeholderSrc: $r('app.media.loading'),
            errorholderSrc: $r('app.media.failed'),
            objectFit: ImageFit.Contain
          }
        }).width(100).height(100)
        Text($r('app.string.Network_images'))
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
        ImageKnifeComponent({
          imageKnifeOption: {
            loadSrc:mapData[MAP_DATA_KEYS[0]],
            placeholderSrc: $r('app.media.loading'),
            errorholderSrc: $r('app.media.failed'),
            objectFit: ImageFit.Contain,
            progressListener:(progress:number)=>{console.info('ImageKnife:: call back progress = ' + progress)},
            // 通过https协议进行连接时,默认使用系统预设CA证书。若希望使用自定义证书进行https连接,则需要将自定义证书上传至应用沙箱目录中,并在caPath中指定该证书所在的应用沙箱路径
            // caPath: '/data/storage/el1/bundle/ca.pem',
          }
        }).width(100).height(100)
        Text($r('app.string.Custom_network_download'))
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
        ImageKnifeComponent({
          imageKnifeOption: {
            loadSrc: PageViewModel.getMenus()[1],
            placeholderSrc: $r('app.media.loading'),
            errorholderSrc: $r('app.media.failed'),
            objectFit: ImageFit.Contain,
            headerOption:[{
              key:'refer',
              value:'xx.xx.xx.xx'
            }],
            customGetImage: custom,
            transformation: new BlurTransformation(10)
          }
        }).width(100).height(100)
        Text($r('app.string.PixelMap_loads_images'))
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
        ImageKnifeComponent({
          imageKnifeOption: {
            loadSrc: this.pixelMap!,
            placeholderSrc: $r('app.media.loading'),
            errorholderSrc: $r('app.media.failed'),
            objectFit: ImageFit.Contain,
          }
        }).width(100).height(100)
      }
      .width('100%')
    }
    .height('100%')
  }

  changePic(buffer: ArrayBuffer){
    let imageSource: image.ImageSource = image.createImageSource(buffer);
    if (imageSource) {
      let decodingOptions: image.DecodingOptions = {
        editable: true,
      }
      imageSource.createPixelMap(decodingOptions,(err,pixelMap)=>{
        imageSource.release()
        this.pixelMap = pixelMap;
      })
    }
  }
}

// 自定义下载方法
@Concurrent
async function custom(context: Context, src: string | PixelMap | Resource,headers?: Record<string,Object>): Promise<ArrayBuffer | undefined> {
  let refer = headers!['refer'] as string
  console.info('ImageKnife::  custom download:' + src,'refer:'+refer)
  // 举例写死从本地文件读取,也可以自己请求网络图片
  let buffer = context.resourceManager.getMediaContentSync($r('app.media.startIcon').id).buffer as ArrayBuffer
  return buffer
}