/**
 * Copyright (c) 2018 Bitbloq (BQ)
 *
 * License: MIT
 *
 * long description for the file
 *
 * @summary short description for the file
 * @author David García <https://github.com/empoalp>,
 * @author Alberto Valero <https://github.com/avalero>
 *
 * Created at     : 2018-11-07 13:45:37
 * Last modified  : 2018-11-29 19:15:29
 */
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import ObjectsCommon from './ObjectsCommon';
import Object3D from './Object3D';
import ObjectsGroup from './ObjectsGroup';
import isEqual from 'lodash.isequal';
import cloneDeep from 'lodash.clonedeep';
import * as THREE from 'three';
/**
 * RepetitionObject Class
 * I allows to repeat one object in a cartesian or polar way.
 */
var RepetitionObject = /** @class */ (function (_super) {
    __extends(RepetitionObject, _super);
    /**
     *
     * @param params The parameters of the repetition
     * @param original The object to repeat
     * Creates an ObjectsGroup with cloned objects (Object3D instance) on their new postion
     */
    function RepetitionObject(params, original, viewOptions, mesh) {
        if (viewOptions === void 0) { viewOptions = ObjectsCommon.createViewOptions(); }
        if (mesh === void 0) { mesh = undefined; }
        var _this = this;
        var vO = __assign({}, ObjectsCommon.createViewOptions(), original.toJSON().viewOptions, viewOptions);
        _this = _super.call(this, vO, []) || this;
        _this.parameters = __assign({}, params);
        _this.originalObject = original;
        _this.originalObject.setParent(_this);
        _this.type = RepetitionObject.typeName;
        _this._meshUpdateRequired = true;
        _this._pendingOperation = true;
        _this.group = [];
        _this.mesh = new THREE.Group();
        _this.lastJSON = _this.toJSON();
        if (mesh) {
            _this.setMesh(mesh);
        }
        else {
            _this.meshPromise = _this.computeMeshAsync();
        }
        return _this;
    }
    /**
     *
     * @param object the object descriptor of the object to be repeated
     * @param scene the scene to which the object belongs
     */
    RepetitionObject.newFromJSON = function (obj, scene) {
        if (obj.type !== RepetitionObject.typeName)
            throw new Error("Types do not match " + RepetitionObject.typeName + ", " + obj.type);
        try {
            var object = scene.getObject(obj.children[0]);
            return new RepetitionObject(obj.parameters, object, obj.viewOptions);
        }
        catch (e) {
            throw new Error("Cannot create RepetitionObject: " + e);
        }
    };
    RepetitionObject.prototype.setMesh = function (mesh) {
        this.mesh = mesh;
        this._meshUpdateRequired = false;
        this._pendingOperation = false;
        this.mesh.updateMatrixWorld(true);
        this.mesh.updateMatrix();
    };
    /**
     * Performs a cartesian repetition of object (nun times), with x,y,z distances
     * It adds repeated objects to ObjectsGroup instance
     */
    RepetitionObject.prototype.cartesianRepetition = function () {
        this.mesh.children.length = 0;
        this.group.length = 0;
        var _a = this
            .parameters, x = _a.x, y = _a.y, z = _a.z, type = _a.type, num = _a.num;
        for (var i = 0; i < num; i++) {
            if (this.originalObject instanceof ObjectsCommon) {
                var objectClone = this.originalObject.clone();
                var json = objectClone.toJSON();
                json.operations.push(ObjectsCommon.createTranslateOperation(i * x, i * y, i * z));
                objectClone.updateFromJSON(json);
                this.group.push(objectClone);
            }
        }
    };
    RepetitionObject.prototype.setParameters = function (parameters) {
        if (!isEqual(parameters, this.parameters)) {
            this.parameters = __assign({}, parameters);
            this._meshUpdateRequired = true;
        }
    };
    RepetitionObject.prototype.clone = function () {
        if (isEqual(this.lastJSON, this.toJSON())) {
            var obj = new RepetitionObject(this.parameters, this.originalObject.clone(), this.viewOptions, this.mesh.clone());
            return obj;
        }
        else {
            var obj = new RepetitionObject(this.parameters, this.originalObject.clone(), this.viewOptions);
            return obj;
        }
    };
    /**
     * Performs a polar repetition of object (nun times), with x or y or z direction and total ange
     * It adds repeated objects to ObjectsGroup instance
     */
    //TODO
    RepetitionObject.prototype.polarRepetition = function () {
        var _a = this
            .parameters, axis = _a.axis, angle = _a.angle, type = _a.type, num = _a.num;
        for (var i = 0; i < num; i++) {
            if (this.originalObject instanceof Object3D) {
                var objectClone = this.originalObject.clone();
                //objectClone.translate(i*x, i*y, i*z);
                this.group.push(objectClone);
            }
            else if (this.originalObject instanceof ObjectsGroup) {
            }
        }
    };
    /**
     * Returns the group (instance of ObjectsGroup) of this RepetitionObject,
     * applying all the operations to children
     */
    RepetitionObject.prototype.getGroup = function () {
        return new ObjectsGroup(this.group);
    };
    RepetitionObject.prototype.toJSON = function () {
        var obj = cloneDeep(__assign({}, _super.prototype.toJSON.call(this), { parameters: this.parameters, children: [this.originalObject.toJSON()] }));
        return obj;
    };
    RepetitionObject.prototype.getOriginal = function () {
        return this.originalObject;
    };
    /**
     * Updates objects belonging to a group. Group members cannot be changed.
     * If group members do not match an Error is thrown
     * @param object ObjectGroup descriptor object
     */
    RepetitionObject.prototype.updateFromJSON = function (object) {
        if (object.id !== this.id)
            throw new Error("ids do not match " + object.id + ", " + this.id);
        if (object.children[0].id !== this.originalObject.getID())
            throw new Error("object child ids do not match " + object.children[0].id + ", " + this.originalObject.getID());
        try {
            this.originalObject.updateFromJSON(object.children[0]);
            this.setParameters(object.parameters);
            this.setOperations(object.operations);
            if (!isEqual(this.lastJSON, this.toJSON())) {
                this.lastJSON = this.toJSON();
                this.meshPromise = this.computeMeshAsync();
                var obj = this.getParent();
                while (obj) {
                    obj.meshUpdateRequired = true;
                    obj.computeMeshAsync();
                    obj = obj.getParent();
                }
            }
        }
        catch (e) {
            throw new Error("Cannot update Group: " + e);
        }
    };
    Object.defineProperty(RepetitionObject.prototype, "meshUpdateRequired", {
        get: function () {
            return this._meshUpdateRequired || this.originalObject.meshUpdateRequired;
        },
        set: function (a) {
            this._meshUpdateRequired = a;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(RepetitionObject.prototype, "pendingOperation", {
        get: function () {
            return this._pendingOperation || this.originalObject.pendingOperation;
        },
        enumerable: true,
        configurable: true
    });
    RepetitionObject.prototype.applyOperationsAsync = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                this.mesh.position.set(0, 0, 0);
                this.mesh.quaternion.setFromEuler(new THREE.Euler(0, 0, 0), true);
                this.mesh.scale.x = 1;
                this.mesh.scale.y = 1;
                this.mesh.scale.y = 1;
                this.operations.forEach(function (operation) {
                    // Translate operation
                    if (operation.type === Object3D.createTranslateOperation().type) {
                        _this.applyTranslateOperation(operation);
                    }
                    else if (operation.type === Object3D.createRotateOperation().type) {
                        _this.applyRotateOperation(operation);
                    }
                    else if (operation.type === Object3D.createScaleOperation().type) {
                        _this.applyScaleOperation(operation);
                    }
                    else if (operation.type === Object3D.createMirrorOperation().type) {
                        _this.applyMirrorOperation(operation);
                    }
                    else {
                        throw Error('ERROR: Unknown Operation');
                    }
                });
                this._pendingOperation = false;
                this.mesh.updateMatrixWorld(true);
                this.mesh.updateMatrix();
                return [2 /*return*/];
            });
        });
    };
    RepetitionObject.prototype.applyMirrorOperation = function (operation) {
        if (operation.plane === 'xy') {
            this.applyScaleOperation(Object3D.createScaleOperation(1, 1, -1));
        }
        else if (operation.plane === 'yz') {
            this.applyScaleOperation(Object3D.createScaleOperation(-1, 1, 1));
        }
        else if (operation.plane === 'zx') {
            this.applyScaleOperation(Object3D.createScaleOperation(1, -1, 1));
        }
    };
    RepetitionObject.prototype.applyTranslateOperation = function (operation) {
        if (operation.relative) {
            this.mesh.translateX(operation.x);
            this.mesh.translateY(operation.y);
            this.mesh.translateZ(operation.z);
        }
        else {
            //absolute x,y,z axis.
            this.mesh.position.x += Number(operation.x);
            this.mesh.position.y += Number(operation.y);
            this.mesh.position.z += Number(operation.z);
        }
    };
    RepetitionObject.prototype.applyRotateOperation = function (operation) {
        var x = THREE.Math.degToRad(Number(operation.x));
        var y = THREE.Math.degToRad(Number(operation.y));
        var z = THREE.Math.degToRad(Number(operation.z));
        if (operation.relative) {
            this.mesh.rotateX(x);
            this.mesh.rotateY(y);
            this.mesh.rotateZ(z);
        }
        else {
            this.mesh.rotateOnWorldAxis(new THREE.Vector3(1, 0, 0), x);
            this.mesh.rotateOnWorldAxis(new THREE.Vector3(0, 1, 0), y);
            this.mesh.rotateOnWorldAxis(new THREE.Vector3(0, 0, 1), z);
        }
    };
    RepetitionObject.prototype.applyScaleOperation = function (operation) {
        if (Number(operation.x) > 0 &&
            Number(operation.y) > 0 &&
            Number(operation.z) > 0)
            this.mesh.scale.set(this.mesh.scale.x * Number(operation.x), this.mesh.scale.y * Number(operation.y), this.mesh.scale.z * Number(operation.z));
    };
    RepetitionObject.prototype.computeMesh = function () {
        this.mesh.children.length = 0;
        this.group.length = 0;
        if (this.parameters.type.toLowerCase() === 'cartesian')
            this.cartesianRepetition();
        else if (this.parameters.type.toLowerCase() === 'polar')
            this.polarRepetition();
        else
            throw new Error('Unknown Repetition Command');
        this._meshUpdateRequired = false;
        this._pendingOperation = false;
    };
    RepetitionObject.prototype.computeMeshAsync = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                this.meshPromise = new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                    var meshes;
                    var _this = this;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (this.meshUpdateRequired ||
                                    this.originalObject.pendingOperation ||
                                    this.originalObject.viewOptionsUpdateRequired) {
                                    this.computeMesh();
                                }
                                return [4 /*yield*/, Promise.all(this.group.map(function (obj) { return obj.getMeshAsync(); }))];
                            case 1:
                                meshes = _a.sent();
                                this.mesh.children.length = 0;
                                meshes.forEach(function (mesh) {
                                    _this.mesh.add(mesh);
                                });
                                return [4 /*yield*/, this.applyOperationsAsync()];
                            case 2:
                                _a.sent();
                                if (this.mesh instanceof THREE.Group)
                                    resolve(this.mesh);
                                else
                                    reject(new Error('Unexpected Error computing RepetitionObject'));
                                return [2 /*return*/];
                        }
                    });
                }); });
                return [2 /*return*/, this.meshPromise];
            });
        });
    };
    RepetitionObject.typeName = 'RepetitionObject';
    return RepetitionObject;
}(ObjectsCommon));
export default RepetitionObject;
//# sourceMappingURL=RepetitionObject.js.map