/* eslint no-console: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-undef: 0 */
/* eslint no-useless-escape: 0 */

import {
  encodeLong,
  fileMd5ToName
} from './base62'
import FileMd5 from './FileMd5'

const fileMd5 = new FileMd5()

const getFileMd5 = file => {
  return new Promise((resolve, reject) => {
    if (!file) reject(new Error('file is undefined'))
    fileMd5.md5(file, (err, md5) => {
      if (err) {
        reject(err)
      } else {
        resolve(md5.toUpperCase())
      }
    })
  })
}

const getFileName = async file => {
  if(file == undefined) return ""
  const {
    name,
    size
  } = file || {}
  const REG = /(?=\.)(\.([^\\\/.]*))*$/; // file extensions
  const result = name.match(REG)
  const extName = result && result.length && result[1]

  const fileMd5 = await getFileMd5(file)
  const fileName = fileMd5ToName(fileMd5)
  const sizeHash = encodeLong(BigInt(size))
  const ret = `r/${fileName}-${sizeHash}${extName}`

  return ret
}
/*
const packFiles = (object, files) => {
  if( !files) return;
  //for( let title in object){
  //  object[title]['title'] = title
  //}
  for(let i in files ){
    let file = files[i]
    object[file.title] = file
  }
}

const unpackFiles = object  => {
  let files = [];
  for(let title in object){
    let item = object[title];
    if(item.change) files.push(item);
  }
  return files
}
*/
const packFiles = (object, files, change=false) => {
  if(files.length == 0) return;
  for(let i in files ){
    let file = files[i]
    for(let j in object){
      if (file.title == object[j].file.title) {
        object[j].file = file
        object[j].file.change = change
      }
    }
  }
}

const unpackFiles = object  => {
  let files = [];
  for(let i in object){
    let item = object[i].file;
    if(item.change) files.push(item);
  }
  return files
}


export {
  getFileMd5,
  getFileName,
  packFiles,
  unpackFiles,
}
