/*
 * 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 { DownsampleStrategy, ImageKnifeOption, } from '@ohos/imageknife';
import { ImageKnifeComponent } from '@ohos/libraryimageknife';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Downsampler } from '@ohos/imageknife/src/main/ets/downsampling/Downsampler';
import { FileTypeUtil } from '@ohos/imageknife/src/main/ets/utils/FileTypeUtil';

@Entry
@Component
struct DownSamplePage {
  @State imageKnifeOption: ImageKnifeOption = {
    loadSrc: $r('app.media.startIcon'),
    placeholderSrc: $r('app.media.loading'),
    errorholderSrc: $r('app.media.app_icon'),
    objectFit: ImageFit.Contain
  }
  isBrightness: boolean = false
  @State beforeSampling: number = 0
  @State afterSampling: number = 0
  @State SamplingList: SamplingType[] = [

    new SamplingType(7, 'AT_LEAST'),
    new SamplingType(1, 'AT_MOST'),

    new SamplingType(2, 'FIT_CENTER_MEMORY'),
    new SamplingType(4, 'FIT_CENTER_QUALITY'),
    new SamplingType(5, 'CENTER_INSIDE_MEMORY'),
    new SamplingType(6, 'CENTER_INSIDE_QUALITY'),
    new SamplingType(0, 'NONE'),

  ]
  @State checked: boolean = false

  updateImageKnifeOption(value: string) {
    if (value === 'NONE') {
      this.imageKnifeOption = {
        loadSrc: $r('app.media.pngSample'),
        placeholderSrc: $r('app.media.loading'),
        errorholderSrc: $r('app.media.app_icon'),
        objectFit: ImageFit.Contain,
        downsampleOf: DownsampleStrategy.NONE
      }
      this.originalPixMap($r('app.media.pngSample'))
      this.afterSamplingFunc($r('app.media.pngSample'))
    } else if (value === 'AT_MOST') {
      this.imageKnifeOption = {
        loadSrc: $r('app.media.pngSample'),
        placeholderSrc: $r('app.media.loading'),
        errorholderSrc: $r('app.media.app_icon'),
        objectFit: ImageFit.Contain,
        downsampleOf: DownsampleStrategy.AT_MOST
      }
      this.originalPixMap($r('app.media.pngSample'))
      this.afterSamplingFunc($r('app.media.pngSample'))
    } else if (value === 'FIT_CENTER_MEMORY') {
      this.imageKnifeOption = {
        loadSrc: $r('app.media.pngSample'),
        placeholderSrc: $r('app.media.loading'),
        errorholderSrc: $r('app.media.app_icon'),
        objectFit: ImageFit.Contain,
        downsampleOf: DownsampleStrategy.FIT_CENTER_MEMORY
      }
      this.originalPixMap($r('app.media.pngSample'))
      this.afterSamplingFunc($r('app.media.pngSample'))
    } else if (value === 'FIT_CENTER_QUALITY') {
      this.imageKnifeOption = {
        loadSrc: $r('app.media.pngSample'),
        placeholderSrc: $r('app.media.loading'),
        errorholderSrc: $r('app.media.app_icon'),
        objectFit: ImageFit.Contain,
        downsampleOf: DownsampleStrategy.FIT_CENTER_QUALITY
      }
      this.originalPixMap($r('app.media.pngSample'))
      this.afterSamplingFunc($r('app.media.pngSample'))
    } else if (value === 'CENTER_INSIDE_MEMORY') {
      this.imageKnifeOption = {
        loadSrc: $r('app.media.pngSample'),
        placeholderSrc: $r('app.media.loading'),
        errorholderSrc: $r('app.media.app_icon'),
        objectFit: ImageFit.Contain,
        downsampleOf: DownsampleStrategy.CENTER_INSIDE_MEMORY
      }
      this.originalPixMap($r('app.media.pngSample'))
      this.afterSamplingFunc($r('app.media.pngSample'))
    } else if (value === 'CENTER_INSIDE_QUALITY') {
      this.imageKnifeOption = {
        loadSrc: $r('app.media.pngSample'),
        placeholderSrc: $r('app.media.loading'),
        errorholderSrc: $r('app.media.app_icon'),
        objectFit: ImageFit.Contain,
        downsampleOf: DownsampleStrategy.CENTER_INSIDE_QUALITY
      }
      this.originalPixMap($r('app.media.pngSample'))
      this.afterSamplingFunc($r('app.media.pngSample'))
    } else {
      this.imageKnifeOption = {
        loadSrc: $r('app.media.pngSample'),
        placeholderSrc: $r('app.media.loading'),
        errorholderSrc: $r('app.media.app_icon'),
        objectFit: ImageFit.Contain,
        downsampleOf: DownsampleStrategy.AT_LEAST
      }
      this.originalPixMap($r('app.media.pngSample'))
      this.afterSamplingFunc($r('app.media.pngSample'))
    }
  }

  async afterSamplingFunc(imgs: Resource) {
    let img: Uint8Array = await getContext(this).resourceManager.getMediaContent(imgs);
    let imageSource: image.ImageSource = image.createImageSource(img.buffer.slice(0));
    let fileTypeUtil = new FileTypeUtil();
    let typeValue = fileTypeUtil.getFileType(img.buffer.slice(0)) as string;
    let decodingOptions: image.DecodingOptions = {
      editable: true,
      desiredPixelFormat: 3,
    }
    let imageInfo = await imageSource.getImageInfo()

    if (this.imageKnifeOption.downsampleOf !== DownsampleStrategy.NONE && this.imageKnifeOption.downsampleOf != undefined ) {
      let reqSize =
        new Downsampler().calculateScaling(typeValue, imageInfo.size.width, imageInfo.size.height, 300,
          300, this.imageKnifeOption.downsampleOf)
      decodingOptions = {
        editable: true,
        desiredSize: {
          width: reqSize.width,
          height: reqSize.height
        }
      }
    }

    // 创建pixelMap
    imageSource.createPixelMap(decodingOptions).then((pixelMap: image.PixelMap) => {
      imageSource.release()
      this.afterSampling = pixelMap.getPixelBytesNumber()
      pixelMap.release()
    }).catch((err: BusinessError) => {
      imageSource.release()
      console.error('Failed to create PixelMap')
    });
  }

  async originalPixMap(imgs: Resource,) {
    let img: Uint8Array = await getContext(this).resourceManager.getMediaContent(imgs);
    let imageSource: image.ImageSource = image.createImageSource(img.buffer.slice(0));
    let decodingOptions: image.DecodingOptions = {
      editable: true,
      desiredPixelFormat: 3,
    }
    // 创建pixelMap
    imageSource.createPixelMap(decodingOptions).then((pixelMap: image.PixelMap) => {
      imageSource.release()
      this.beforeSampling = pixelMap.getPixelBytesNumber()
      pixelMap.release()
    }).catch((err: BusinessError) => {
      imageSource.release()
      console.error('Failed to create PixelMap')
    });
  }
  getResourceString(res:Resource){
    return getContext().resourceManager.getStringSync(res.id)
  }
  build() {
    Scroll() {
      Column() {
        ForEach(this.SamplingList, (item: SamplingType, index) => {
          Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
            Radio({ value: item.value + 'radio', group: 'radioGroup' })
              .height(50)
              .width(50)
              .checked(this.checked)
              .onClick(() => {
                this.updateImageKnifeOption(item.value)
              })
            Text(this.getResourceString($r('app.string.Sampling_pecification'))+ item.value).fontSize(20)
          }
        }, (item: SamplingType) => JSON.stringify(item))
        Column() {
          Text(`${this.getResourceString($r('app.string.Unreal_samples'))}:${this.beforeSampling}`).fontSize(20)
          Text(`${ this.getResourceString($r('app.string.After_the_sampling'))}:${this.afterSampling}`).fontSize(20)
        }

        ImageKnifeComponent({
          imageKnifeOption: this.imageKnifeOption
        })
          .height(px2vp(300))
          .width(px2vp(300))
          .borderWidth(1)
          .borderColor(Color.Pink)
      }

    }
    .height('100%')
    .width('100%')
  }
}

class SamplingType {
  key: number
  value: string

  constructor(key: number, value: string) {
    this.key = key
    this.value = value
  }
}