const system = require('../../../system');
const CtlBase = require('../../ctl.base');
const crypto = require('crypto');
const fs = require('fs');
const accesskey = '3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
const accessKeyId = 'LTAI4GC5tSKvqsH2hMqj6pvd';
const url = 'https://gsb-zc.oss-cn-beijing.aliyuncs.com';
class UploadCtl extends CtlBase {
  constructor() {
    super('common', CtlBase.getServiceName(UploadCtl));
    this.cmdPdf2HtmlPattern = 'docker run -i --rm -v /tmp/:/pdf 0c  pdf2htmlEX --zoom 1.3 \'{fileName}\'';
    this.restS = system.getObject('util.execClient');
    this.cmdInsertToFilePattern = 'sed -i \'s/id="page-container"/id="page-container" contenteditable="true"/\'';
    // sed -i  's/1111/&BBB/' /tmp/input.txt
    // sed 's/{position}/{content}/g' {path}
  }
  async getOssConfig() {
    const policyText = {
      expiration: '2119-12-31T16:00:00.000Z',
      conditions: [
        ['content-length-range', 0, 1048576000],
        ['starts-with', '$key', 'zc'],
      ],
    };
    const b = new Buffer(JSON.stringify(policyText));
    const policyBase64 = b.toString('base64');
    const signature = crypto.createHmac('sha1', accesskey).update(policyBase64)
      .digest()
      .toString('base64'); // base64

    const data = {
      OSSAccessKeyId: accessKeyId,
      policy: policyBase64,
      Signature: signature,
      Bucket: 'gsb-zc',
      success_action_status: 201,
      url,
    };

    return data;
  };
  async upfile(srckey, dest) {
    const oss = system.getObject('util.ossClient');
    const result = await oss.upfile(srckey, `/tmp/${dest}`);
    return result;
  };
  async downfile(srckey) {
    const oss = system.getObject('util.ossClient');
    let downfile = await oss.downfile(srckey).then(() => {
      downfile = `/tmp/${srckey}`;
      return downfile;
    });
    return downfile;
  };
  async pdf2html(obj) {
    const srckey = obj.key;
    const downfile = await this.downfile(srckey);
    const cmd = this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
    const rtn = await this.restS.exec(cmd);
    const path = `/tmp/${srckey.split('.pdf')[0]}.html`;
    const a = await this.insertToFile(path);
    fs.unlink(`/tmp/${srckey}`);
    const result = await this.upfile(`${srckey.split('.pdf')[0]}.html`, `${srckey.split('.pdf')[0]}.html`);
    return result.url;
  };
  async insertToFile(path) {
    const cmd = `${this.cmdInsertToFilePattern} ${path}`;
    return await this.restS.exec(cmd);
  };
}
module.exports = UploadCtl;
