const FileSystemBlobStore = require('./fileSystemBlobStore')
const fs = require('fs')

/**
 *  @classdesc
 * File store with automatic conversion MS Word, MS Excel and MS PowerPoint documents into \*.pdf format.
 *
 * Require MS Office installed on the server - see
 * <a href="https://enviance.softline.kiev.ua/confluence/pages/viewpage.action?pageId=65274525#Installation(requirements)-UsingMicrosoftWordasservice"> requirement</a>
 *
 * singleton
 */
class FileSystemPDFBlobStore extends FileSystemBlobStore {
  /**
   * @inheritDoc
   * @param {BlobStoreRequest} request Request params
   * @param {UBEntityAttribute} attribute
   * @param {ArrayBuffer|THTTPRequest} content
   * @returns {BlobStoreItem}
   */
  saveContentToTempStore (request, attribute, content) {
    const fn = this.getTempFileName(request)
    // TODO - call convertion service here and store PDF to temp instead of doc/docx
    if (content.writeToFile) {
      if (!content.writeToFile(fn)) throw new Error(`Error write to ${fn}`)
    } else {
      fs.writeFileSync(fn, content)
    }
    const origFn = request.fileName
    const ct = this.getMimeType(origFn)
    return {
      store: this.name,
      fName: origFn,
      origName: origFn,
      ct,
      size: content.byteLength,
      md5: '',
      isDirty: true
    }
  }
}

module.exports = FileSystemPDFBlobStore