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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 { AcGeMatrix3d, AcGePoint3d } from '@mlightcad/data-model';
import { AcApAnnotation, AcApDocManager } from '../app';
import { AcEdCommand } from '../command';
import { AcEdOpenMode, AcEdPreviewJig, AcEdPromptPointOptions, AcEdPromptSelectionOptions, AcEdPromptStateMachine, AcEdPromptStatus } from '../editor';
import { AcApI18n } from '../i18n';
/**
 * MOVE preview jig.
 *
 * It clones source entities once in memory and updates those clones by
 * incremental translations during mouse move, so the database entities are
 * untouched until command commit.
 */
var AcApMovePreviewJig = /** @class */ (function (_super) {
    __extends(AcApMovePreviewJig, _super);
    function AcApMovePreviewJig(view, sourceEntities, basePoint) {
        var _this = _super.call(this, view) || this;
        _this._view = view;
        _this._basePoint = new AcGePoint3d(basePoint);
        _this._lastDisplacement = new AcGePoint3d(0, 0, 0);
        _this._previewEntities = sourceEntities
            .map(function (entity) { return _this.cloneEntity(entity); })
            .filter(function (entity) { return !!entity; });
        return _this;
    }
    Object.defineProperty(AcApMovePreviewJig.prototype, "entity", {
        get: function () {
            var _a;
            return (_a = this._previewEntities[0]) !== null && _a !== void 0 ? _a : null;
        },
        enumerable: false,
        configurable: true
    });
    AcApMovePreviewJig.prototype.update = function (point) {
        if (this._previewEntities.length === 0)
            return;
        var displacement = new AcGePoint3d(point.x - this._basePoint.x, point.y - this._basePoint.y, point.z - this._basePoint.z);
        var delta = new AcGePoint3d(displacement.x - this._lastDisplacement.x, displacement.y - this._lastDisplacement.y, displacement.z - this._lastDisplacement.z);
        var hasDelta = delta.x !== 0 || delta.y !== 0 || delta.z !== 0;
        if (!hasDelta)
            return;
        var matrix = new AcGeMatrix3d().makeTranslation(delta.x, delta.y, delta.z);
        this._previewEntities.forEach(function (entity) { return entity.transformBy(matrix); });
        this._lastDisplacement = displacement;
    };
    AcApMovePreviewJig.prototype.render = function () {
        if (this._previewEntities.length === 0)
            return;
        this._view.addTransientEntity(this._previewEntities);
    };
    AcApMovePreviewJig.prototype.end = function () {
        var _this = this;
        this._previewEntities.forEach(function (entity) {
            return _this._view.removeTransientEntity(entity.objectId);
        });
    };
    AcApMovePreviewJig.prototype.cloneEntity = function (entity) {
        return entity.clone();
    };
    return AcApMovePreviewJig;
}(AcEdPreviewJig));
/**
 * Command to move selected entities by a displacement vector.
 *
 * Behavior (AutoCAD-like):
 * 1) Select entities (or reuse preselection),
 * 2) Specify base point or choose `Displacement`,
 * 3) Specify second point (or displacement point),
 * 4) Apply translation to all selected entities.
 */
var AcApMoveCmd = /** @class */ (function (_super) {
    __extends(AcApMoveCmd, _super);
    function AcApMoveCmd() {
        var _this = _super.call(this) || this;
        _this.mode = AcEdOpenMode.Review;
        return _this;
    }
    AcApMoveCmd.prototype.execute = function (context) {
        return __awaiter(this, void 0, void 0, function () {
            var selectionSet, annotation, blockTable, selectionIds, _a, ids, sourceEntities, basePoint, displacement, createDisplacementKeyword, BasePointState, SecondPointState, DisplacementState, machine, matrix;
            var _b, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        selectionSet = context.view.selectionSet;
                        annotation = new AcApAnnotation(context.doc.database);
                        blockTable = context.doc.database.tables.blockTable;
                        if (!(selectionSet.count > 0)) return [3 /*break*/, 1];
                        _a = selectionSet.ids;
                        return [3 /*break*/, 3];
                    case 1: return [4 /*yield*/, AcApDocManager.instance.editor.getSelection(new AcEdPromptSelectionOptions(AcApI18n.sysCmdPrompt('move')))];
                    case 2:
                        _a = ((_c = (_b = (_d.sent()).value) === null || _b === void 0 ? void 0 : _b.ids) !== null && _c !== void 0 ? _c : []);
                        _d.label = 3;
                    case 3:
                        selectionIds = _a;
                        if (selectionIds.length === 0)
                            return [2 /*return*/];
                        ids = context.doc.openMode == AcEdOpenMode.Review
                            ? annotation.filterAnnotationEntities(selectionIds)
                            : selectionIds;
                        if (ids.length === 0) {
                            selectionSet.clear();
                            return [2 /*return*/];
                        }
                        sourceEntities = ids
                            .map(function (id) { return blockTable.getEntityById(id); })
                            .filter(function (entity) { return !!entity; });
                        if (sourceEntities.length === 0) {
                            selectionSet.clear();
                            return [2 /*return*/];
                        }
                        createDisplacementKeyword = function (prompt) {
                            prompt.keywords.add(AcApI18n.t('jig.move.keywords.displacement.display'), AcApI18n.t('jig.move.keywords.displacement.global'), AcApI18n.t('jig.move.keywords.displacement.local'));
                        };
                        BasePointState = /** @class */ (function () {
                            function BasePointState(machine) {
                                this.machine = machine;
                            }
                            BasePointState.prototype.buildPrompt = function () {
                                var prompt = new AcEdPromptPointOptions(AcApI18n.t('jig.move.basePointOrDisplacement'));
                                createDisplacementKeyword(prompt);
                                return prompt;
                            };
                            BasePointState.prototype.handleResult = function (result) {
                                return __awaiter(this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        if (result.status === AcEdPromptStatus.OK) {
                                            basePoint = new AcGePoint3d(result.value);
                                            this.machine.setState(new SecondPointState(this.machine));
                                            return [2 /*return*/, 'continue'];
                                        }
                                        if (result.status === AcEdPromptStatus.Keyword &&
                                            result.stringResult === 'Displacement') {
                                            this.machine.setState(new DisplacementState());
                                            return [2 /*return*/, 'continue'];
                                        }
                                        return [2 /*return*/, 'finish'];
                                    });
                                });
                            };
                            return BasePointState;
                        }());
                        SecondPointState = /** @class */ (function () {
                            function SecondPointState(machine) {
                                this.machine = machine;
                            }
                            SecondPointState.prototype.buildPrompt = function () {
                                var prompt = new AcEdPromptPointOptions(AcApI18n.t('jig.move.secondPointOrDisplacement'));
                                createDisplacementKeyword(prompt);
                                if (basePoint) {
                                    prompt.useBasePoint = true;
                                    prompt.useDashedLine = true;
                                    prompt.basePoint = basePoint;
                                    prompt.jig = new AcApMovePreviewJig(context.view, sourceEntities, basePoint);
                                }
                                return prompt;
                            };
                            SecondPointState.prototype.handleResult = function (result) {
                                return __awaiter(this, void 0, void 0, function () {
                                    var secondPoint;
                                    return __generator(this, function (_a) {
                                        if (result.status === AcEdPromptStatus.OK && basePoint) {
                                            secondPoint = new AcGePoint3d(result.value);
                                            displacement = new AcGePoint3d(secondPoint.x - basePoint.x, secondPoint.y - basePoint.y, secondPoint.z - basePoint.z);
                                            return [2 /*return*/, 'finish'];
                                        }
                                        if (result.status === AcEdPromptStatus.Keyword &&
                                            result.stringResult === 'Displacement') {
                                            this.machine.setState(new DisplacementState());
                                            return [2 /*return*/, 'continue'];
                                        }
                                        return [2 /*return*/, 'finish'];
                                    });
                                });
                            };
                            return SecondPointState;
                        }());
                        DisplacementState = /** @class */ (function () {
                            function DisplacementState() {
                            }
                            DisplacementState.prototype.buildPrompt = function () {
                                var prompt = new AcEdPromptPointOptions(AcApI18n.t('jig.move.displacement'));
                                prompt.useBasePoint = true;
                                prompt.useDashedLine = true;
                                prompt.basePoint = new AcGePoint3d(0, 0, 0);
                                prompt.jig = new AcApMovePreviewJig(context.view, sourceEntities, prompt.basePoint);
                                return prompt;
                            };
                            DisplacementState.prototype.handleResult = function (result) {
                                return __awaiter(this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        if (result.status === AcEdPromptStatus.OK) {
                                            displacement = new AcGePoint3d(result.value);
                                        }
                                        return [2 /*return*/, 'finish'];
                                    });
                                });
                            };
                            return DisplacementState;
                        }());
                        machine = new AcEdPromptStateMachine();
                        machine.setState(new BasePointState(machine));
                        return [4 /*yield*/, machine.run(function (prompt) { return AcApDocManager.instance.editor.getPoint(prompt); })];
                    case 4:
                        _d.sent();
                        if (!displacement) {
                            selectionSet.clear();
                            return [2 /*return*/];
                        }
                        matrix = new AcGeMatrix3d().makeTranslation(displacement.x, displacement.y, displacement.z);
                        ids.forEach(function (id) {
                            var entity = blockTable.getEntityById(id);
                            if (!entity)
                                return;
                            entity.transformBy(matrix);
                            entity.triggerModifiedEvent();
                        });
                        selectionSet.clear();
                        return [2 /*return*/];
                }
            });
        });
    };
    return AcApMoveCmd;
}(AcEdCommand));
export { AcApMoveCmd };
//# sourceMappingURL=AcApMoveCmd.js.map