import {injectable} from 'inversify';
import {DecryptAndUnTarOptions} from "../../interfaces/vita-options-results";
import {autoserialize} from 'cerialize';

const fileExists = require('file-exists');
const path = require('path');

@injectable()
export class DecryptAndUnTarOptionsImpl implements DecryptAndUnTarOptions {
  @autoserialize encryptedFiles: string[] = [];
  @autoserialize foldersOfEncryptedFiles: string[] = [];
  @autoserialize encryptedFilePattern: RegExp;
  @autoserialize targetFolder: string = '';
  @autoserialize password: string = '';

  fromArgv(argv: any) {
    this.encryptedFiles = argv.input || '';
    this.password = argv.password || '';
  }

  validate() {
    if(!this.encryptedFiles || !this.encryptedFiles.length){
      throw new Error('The DecryptAndUnTarOptions.encryptedFiles array must contain at least one encrypted file');
    }
    this.encryptedFiles.forEach(encryptedFile=>{
      if(!fileExists(encryptedFile)){
        throw new Error(`Encrypted file '${encryptedFile}' does not exist`);
      }
    });
    if(!this.password){
      throw new Error('The DecryptAndUnTarOptions.password cannot be empty');
    }
    if (!this.targetFolder) {
      let randomInt = Math.floor((Math.random() * 9000) + 1000);
      this.targetFolder = path.resolve('/tmp', `vitaWorkDir-${randomInt}`);
    }
  }
}
