import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import fs from '@ohos.file.fs';

let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;

export class FileUtils {
  public fd: number = 0;
  public offset: number = 0;
  public length: number = 0;

  static async copyAssetsFileToApp(child: string): Promise<void> {

    fs.mkdir(filesDir + "/" + child)

    // 传入""表示获取rawfile根目录下的文件列表
    await context.resourceManager.getRawFileList("").then(async  (value: Array<string>) => {
      // let rawFile = value;
      console.log("rawFile size: %d", value.length);

      value.forEach((item: string, index: number)=>{

        const destFile = filesDir + "/" + child + '/' + item
        if (!fs.accessSync(destFile)){
          context.resourceManager.getRawFileContent(item).then(async (data: Uint8Array)=>{
            console.log("getRawFileContent[%s] size: %d", item, data.length);

            await fs.open(destFile, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then(async (file)=>{
              await fs.write(file.fd, data.buffer).then((len: number)=>{
                console.log("write rawFile size: %d", len);
              })
            })
          })
        }


      })

    }).catch((error: BusinessError) => {
      console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
    });

  }

  static async isFileExsit(file: string){

  }
}