'use strict';

const ftp = require('basic-ftp');

// const fs = require('fs');

class FTPClient {
  constructor(host = 'localhost', port = 21, username = 'anonymous', password = 'guest', secure = false, secureOptions = '') {
    this.client = new ftp.Client();
    // this.client.ftp.verbose = true;
    this.settings = {
      host: host,
      port: port,
      user: username,
      password: password,
      secure: secure,
      secureOptions: secureOptions
    };
  }

  async upload(sourcePath, remotePath, permissions) {
    let self = this;
    try {
      let access = await self.client.access(self.settings);
      let upload = await self.client.uploadFrom(sourcePath, remotePath);
      // let permissions = await self.changePermissions(permissions.toString(), remotePath);
      self.client.close();
      return true;
    } catch (err) {
      console.log('upload ERR: ', err);
      self.client.close();
      return false;
    }
  }

  async createDir(miadir) {
    let access = await this.client.access(this.settings);
    await this.client.ensureDir(miadir);
  }

  close() {
    this.client.close();
  }

  changePermissions(perms, filepath) {
    let cmd = 'SITE CHMOD ' + perms + ' ' + filepath;
    return this.client.send(cmd, false);
  }
}


module.exports = FTPClient;
