import * as opentype from 'opentype.js'

const hex = (buffer:ArrayBuffer)=>{
  let code = [];
  let view = new DataView(buffer);
  for (var i = 0; i < view.byteLength; i += 4) {
      let value = view.getUint32(i)
      let stringValue = value.toString(16)
      // 填充切片
      let padding = '00000000'
      let paddedValue = (padding + stringValue).slice(-padding.length)
      code.push(paddedValue);
  }
  return code.join("");
}

const randomString = (e:number) => {    
  e = e || 32;
  var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
  a = t.length,
  n = "";
  for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
  return n+(new Date().getTime())
}

export const reduceFont = async (fontFile: File) => {
  const buff = await fontFile.arrayBuffer()
  let fontb = opentype.parse(buff)
  let saveWords = fontb.names.fontFamily.zh??fontb.names.fontFamily.en
  saveWords ="A"+saveWords
  let savePosition:any[] = []
  for (let i = 0; i < saveWords.length; i++) {
    let g=fontb.encoding.charToGlyphIndex(saveWords[i]);
    if (g>=0){
      savePosition.push(fontb.glyphs.get(g))
    }
  }
  const glyphs = savePosition;
  const font = new opentype.Font({
    familyName: 'newFont',
    styleName: 'regular',
    unitsPerEm: fontb.unitsPerEm,
    ascender: fontb.ascender,
    descender: fontb.descender,
    glyphs: glyphs
  });
  let newBuff = font.toBuffer();
  let fileName = randomString(6)+".otf"
  let newFile = new File([newBuff],fileName)
  return {
    file:newFile,
    name:fontb.names.fontFamily.zh??fontb.names.fontFamily.en
  }
  //font.download();
}