'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _axios = require('axios');

var _axios2 = _interopRequireDefault(_axios);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _formData = require('form-data');

var _formData2 = _interopRequireDefault(_formData);

var _debug = require('../debug');

var _debug2 = _interopRequireDefault(_debug);

var _session = require('../session');

var _session2 = _interopRequireDefault(_session);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const REGISTRY_TIMEOUT = 60000;

const { debug } = (0, _debug2.default)('utils-registry');

class Registry {
  constructor() {
    debug('Registry.constructor');

    const registryInstance = process.env.SYNCANO_SOCKET_REGISTRY_INSTANCE || 'socket-registry';
    this.registryHost = `${registryInstance}.${_session2.default.ENDPOINT_HOST}`;
    this.registryHostUrl = `https://${this.registryHost}`;

    this.fileStorageHost = _session2.default.getHost();
    this.fileStorageEndpoint = `/v2/instances/${registryInstance}/classes/storage/objects/`;

    if (_session2.default.project) {
      this.installEndpoint = `/v2/instances/${_session2.default.project.instance}/sockets/install/`;
      this.installUrl = `https://${_session2.default.getHost()}${this.installEndpoint}`;
    }
  }

  getFullSocket(name, version) {
    return this.searchSocketByName(name, version);
    // .then((socket) => { Registry.getSocket(socket) });
  }

  searchSocketByName(name, version) {
    debug(`searchSocketByName: ${name} (${version})`);
    return _axios2.default.request({
      url: `https://${this.registryHost}/registry/get/`,
      method: 'POST',
      timeout: REGISTRY_TIMEOUT,
      data: {
        name,
        version
      },
      headers: {
        'X-Syncano-Account-Key': _session2.default.settings.account.getAuthKey()
      }
    }).then(response => response.data);
  }

  static getSocket(socket) {
    debug('getSocket');

    const fileName = _path2.default.join(_session2.default.getBuildPath(), `${socket.name}.zip`);
    const file = _fs2.default.createWriteStream(fileName);
    return new Promise((resolve, reject) => {
      _https2.default.get(socket.url, response => {
        response.pipe(file);
        file.on('finish', () => {
          debug('Socket zip downlaoded');
          file.close(resolve);
        });
      });
    });
  }

  publishSocket(socketName, version) {
    debug('publishSocket', socketName);
    return _axios2.default.request({
      url: `${this.registryHostUrl}/registry/publish/`,
      method: 'POST',
      timeout: REGISTRY_TIMEOUT,
      data: {
        name: socketName,
        version
      },
      headers: {
        'X-Syncano-Account-Key': _session2.default.settings.account.getAuthKey()
      }
    }).then(response => response.data);
  }

  searchSocketsByAll(keyword) {
    return _axios2.default.request({
      url: `${this.registryHostUrl}/registry/search/`,
      method: 'POST',
      timeout: REGISTRY_TIMEOUT,
      data: { keyword },
      headers: {
        'X-Syncano-Account-Key': _session2.default.settings.account.getAuthKey()
      }
    }).then(response => response.data);
  }

  submitSocket(socket) {
    return socket.createZip({ plainSources: true }).then(() => _axios2.default.request({
      url: `${this.registryHostUrl}/registry/upload/`,
      method: 'POST',
      timeout: REGISTRY_TIMEOUT,
      headers: {
        'X-Syncano-Account-Key': _session2.default.settings.account.getAuthKey()
      }
    }).then(response => response.data.url)).then(url => new Promise((resolve, reject) => {
      debug('Socket compiled');
      const form = new _formData2.default();
      form.append('file', _fs2.default.createReadStream(socket.getSocketZip()));

      form.submit({
        method: 'PATCH',
        protocol: 'https:',
        host: _session2.default.getHost(),
        path: url
      }, (err, res) => {
        if (err) {
          debug('Error while uploading file');
          reject(err);
        }
        res.on('data', data => {
          debug('Upload done');
          resolve(data);
        });
      });
    })).then(resp => {
      debug('File sent compiled', resp.status);
      const fileObj = JSON.parse(resp);
      return _axios2.default.request({
        url: `${this.registryHostUrl}/registry/add/`,
        method: 'POST',
        timeout: REGISTRY_TIMEOUT,
        data: {
          name: socket.spec.name,
          description: socket.spec.description,
          version: socket.spec.version,
          keywords: socket.spec.keywords,
          url: fileObj.file.value,
          config: socket.getFullConfig()
        },
        headers: {
          'X-Syncano-Account-Key': _session2.default.settings.account.getAuthKey()
        }
      });
    });
  }
}

exports.default = Registry;
module.exports = exports['default'];
//# sourceMappingURL=registry.js.map