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 };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { AcCmEventManager } from '@mlightcad/data-model';
import { AcApDocManager } from '../../app';
import { AcEdCursorManager } from './AcEdCursorManager';
import { AcEdSelectionSet } from './AcEdSelectionSet';
import { AcEdPromptSelectionResult, AcEdPromptStatus } from './prompt';
import { AcEdInputManager } from './ui';
/**
 * Advanced input handler for CAD operations providing high-level user interaction methods.
 *
 * This class serves as a wrapper for all types of user input including:
 * - Point input (mouse clicks, coordinates)
 * - Entity selection (single or multiple entities)
 * - String, number, angle, and distance input
 * - Cursor management and visual feedback
 *
 * The editor abstracts away low-level mouse and keyboard events, providing a clean API
 * for command implementations. Instead of listening to raw DOM events, commands should
 * use the methods provided by this class.
 *
 * @example
 * ```typescript
 * // Get user input for a point
 * const point = await editor.getPoint();
 * console.log('User clicked at:', point);
 *
 * // Get entity selection
 * const selection = await editor.getSelection();
 * console.log('Selected entities:', selection.ids);
 *
 * // Change cursor appearance
 * editor.setCursor(AcEdCorsorType.Crosshair);
 * ```
 */
var AcEditor = /** @class */ (function () {
    /**
     * Creates a new editor instance for the specified view.
     *
     * @param view - The view that this editor will handle input for
     */
    function AcEditor(view) {
        /**
         * Editor events
         */
        this.events = {
            /**
             * Fired after a system variable is changed directly through the SETVAR command or
             * by entering the variable name at the command line.
             */
            sysVarChanged: new AcCmEventManager(),
            /** Fired just before the command starts executing */
            commandWillStart: new AcCmEventManager(),
            /** Fired after the command finishes executing */
            commandEnded: new AcCmEventManager()
        };
        this._view = view;
        this._cursorManager = new AcEdCursorManager(view);
        this._inputManager = new AcEdInputManager(view);
    }
    Object.defineProperty(AcEditor.prototype, "isActive", {
        /**
         * The flag to indicate whether it is currently in an “input acquisition” mode (e.g., point
         * selection, distance/angle prompt, string prompt, etc.),
         */
        get: function () {
            return this._inputManager.isActive;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AcEditor.prototype, "isEntitySelectionActive", {
        /**
         * Whether the current input session explicitly allows entity selection.
         */
        get: function () {
            return this._inputManager.isEntitySelectionActive;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Current modifier key state (Ctrl/Shift/Alt/Meta) during input sessions.
     */
    AcEditor.prototype.getInputModifiers = function () {
        return this._inputManager.modifiers;
    };
    /**
     * Toggle-style input states (e.g. Ctrl-press flip) during input sessions.
     */
    AcEditor.prototype.getInputToggles = function () {
        return this._inputManager.toggles;
    };
    /** Reset toggle-style inputs to their default state. */
    AcEditor.prototype.resetInputToggles = function () {
        this._inputManager.resetToggles();
    };
    /**
     * Queues scripted command-line inputs for subsequent getXXX prompts.
     * One entry equals one Enter-confirmed input.
     */
    AcEditor.prototype.enqueueScriptInputs = function (inputs) {
        this._inputManager.enqueueScriptInputs(inputs);
    };
    /** Clears any queued scripted inputs. */
    AcEditor.prototype.clearScriptInputs = function () {
        this._inputManager.clearScriptInputs();
    };
    Object.defineProperty(AcEditor.prototype, "currentCursor", {
        /**
         * Gets the currently active cursor type.
         *
         * @returns The current cursor type, or undefined if none is set
         */
        get: function () {
            return this._currentCursor;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Restores the previously set cursor.
     *
     * This is useful for temporarily changing the cursor and then reverting
     * to the previous state.
     */
    AcEditor.prototype.restoreCursor = function () {
        if (this._previousCursor != null) {
            this.setCursor(this._previousCursor);
        }
    };
    /**
     * Sets the cursor appearance for the view.
     *
     * The previous cursor type is stored for potential restoration.
     *
     * @param cursorType - The cursor type to set
     *
     * @example
     * ```typescript
     * editor.setCursor(AcEdCorsorType.Crosshair);  // For precise point input
     * editor.setCursor(AcEdCorsorType.Grab);       // For pan operations
     * ```
     */
    AcEditor.prototype.setCursor = function (cursorType) {
        this._cursorManager.setCursor(cursorType);
        this._previousCursor = this._currentCursor;
        this._currentCursor = cursorType;
    };
    /**
     * Temporarily sets a new cursor for the duration of a function execution.
     *
     * This method saves the current cursor, sets the new cursor, executes the provided function,
     * and then restores the original cursor regardless of whether the function succeeds or fails.
     *
     * @param cursorType - The cursor type to use temporarily
     * @param action - The function to execute with the temporary cursor
     * @returns The result of the executed function
     *
     * @example
     * ```typescript
     * // Temporarily set grab cursor for a pan operation
     * await editor.withCursor(AcEdCorsorType.Grab, async () => {
     *   // Perform pan operation
     *   await this.performPan();
     * });
     * // Cursor is automatically restored to previous state
     * ```
     */
    AcEditor.prototype.withCursor = function (cursorType, action) {
        return __awaiter(this, void 0, void 0, function () {
            var originalCursor;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        originalCursor = this._currentCursor;
                        this.setCursor(cursorType);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 3, 4]);
                        return [4 /*yield*/, Promise.resolve(action())];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        if (originalCursor !== undefined) {
                            this.setCursor(originalCursor);
                        }
                        else {
                            this.restoreCursor();
                        }
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sets the cursor color for the crosshair cursor
     *
     * @param color - The color for the cursor
     */
    AcEditor.prototype.setCursorColor = function (color) {
        this._cursorManager.setCursorColor(color);
    };
    /**
     * Prompts the user to input a point by clicking on the view or inputting
     * one coordinate value.
     *
     * This method returns a promise that resolves after the user clicks
     * on the view or inputs one valid coordinate value, providing the
     * world coordinates of the click point.
     *
     * @returns Promise that resolves to the input point coordinates
     */
    AcEditor.prototype.getPoint = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getPoint(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to input an angle by clicking on the view or input
     * one number.
     *
     * This method returns a promise that resolves after the user clicks
     * on the view or inputs one valid angle value.
     *
     * @returns Promise that resolves to the input angle value.
     */
    AcEditor.prototype.getAngle = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getAngle(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to input a distance by clicking on the view or input
     * one number.
     *
     * This method returns a promise that resolves after the user clicks
     * on the view or inputs one valid distance value.
     *
     * @returns Promise that resolves to the input distance value.
     */
    AcEditor.prototype.getDistance = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getDistance(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to input a double value.
     *
     * @returns Promise that resolves to the input double value.
     */
    AcEditor.prototype.getDouble = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getDouble(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to input an integer value.
     *
     * @returns Promise that resolves to the input integer value.
     */
    AcEditor.prototype.getInteger = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getInteger(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to input a string.
     *
     * @returns Promise that resolves to the input one string.
     */
    AcEditor.prototype.getString = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getString(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to input a keyword.
     *
     * @returns Promise that resolves to the input one keyword.
     */
    AcEditor.prototype.getKeywords = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getKeywords(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to input a keyword.
     *
     * @returns Promise that resolves to the input one keyword.
     */
    AcEditor.prototype.getEntity = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getEntity(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to select entities using box selection.
     *
     * This method allows the user to drag a selection box to select
     * multiple entities at once. The selection behavior follows CAD
     * conventions (left-to-right for window, right-to-left for crossing).
     *
     * @returns Promise that resolves to the selection set containing selected entity IDs
     */
    AcEditor.prototype.getSelection = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getSelection(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Prompts the user to specify a rectangular bounding box (two corners).
     *
     * @returns Promise that resolves to rectangular bounding box.
     */
    AcEditor.prototype.getBox = function (options) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._inputManager.getBox(options)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * Selects all objects in model space that satisfy the specified filter.
     *
     * This method is analogous to AutoCAD .NET `Editor.SelectAll(SelectionFilter)`,
     * but it does not modify the current view selection set directly. Instead, it
     * returns an independent {@link AcEdPromptSelectionResult}.
     *
     * @param filter - Optional typed-value filter expression
     * @returns Selection result containing all matched object ids
     */
    AcEditor.prototype.selectAll = function (filter) {
        var e_1, _a;
        try {
            var modelSpace = AcApDocManager.instance.curDocument.database.tables.blockTable
                .modelSpace;
            var ids = [];
            try {
                for (var _b = __values(modelSpace.newIterator()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var entity = _c.value;
                    if (!filter || filter.matches(entity)) {
                        ids.push(entity.objectId);
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return new AcEdPromptSelectionResult(AcEdPromptStatus.OK, new AcEdSelectionSet(ids));
        }
        catch (_d) {
            return new AcEdPromptSelectionResult(AcEdPromptStatus.Error);
        }
    };
    return AcEditor;
}());
export { AcEditor };
//# sourceMappingURL=AcEditor.js.map