"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _object() {
  const data = _interopRequireDefault(require("./objects/object"));

  _object = function () {
    return data;
  };

  return data;
}

function _utils() {
  const data = require("../utils");

  _utils = function () {
    return data;
  };

  return data;
}

function _objectRegistrar() {
  const data = require("./object-registrar");

  _objectRegistrar = function () {
    return data;
  };

  return data;
}

// import logger from '../logger/logger';
class ComponentObjects {
  constructor(component, objects) {
    this.component = component;
    this.objects = objects;
  }

  toString() {
    return JSON.stringify({
      component: (0, _utils().toBase64ArrayBuffer)(this.component),
      objects: this.objects.map(_utils().toBase64ArrayBuffer)
    });
  } // Used mainly by server side hooks


  getParsedComponent() {
    const component = _object().default.parseSync(this.component, _objectRegistrar().typesObj);

    return component;
  } // @TODO optimize ASAP.


  static fromString(str) {
    return ComponentObjects.fromObject(JSON.parse(str));
  }

  static manyToString(componentsAndObjects) {
    const result = JSON.stringify(componentsAndObjects.map(componentAndObject => componentAndObject.toString()));
    return result;
  }

  static manyFromString(str) {
    return JSON.parse(str).map(componentObject => ComponentObjects.fromString(componentObject));
  }

  static fromObject(object) {
    const {
      component,
      objects
    } = object;
    return new ComponentObjects(_from64Buffer(component), objects.map(_from64Buffer));
  }
  /**
   * prefer using `this.toObjectsAsync()` if not must to be sync.
   */


  toObjects(repo) {
    return {
      component: _object().default.parseSync(this.component, repo.types),
      objects: this.objects.map(obj => _object().default.parseSync(obj, repo.types))
    };
  }
  /**
   * see `this.toObject()` for the sync version
   */


  toObjectsAsync(repo) {
    var _this = this;

    return (0, _bluebird().coroutine)(function* () {
      return {
        component: yield _object().default.parseObject(_this.component, repo.types),
        objects: yield Promise.all(_this.objects.map(obj => _object().default.parseObject(obj, repo.types)))
      };
    })();
  }

}

exports.default = ComponentObjects;

function _from64Buffer(val) {
  return Buffer.from(val, 'base64');
}