"use strict";
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 __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;
    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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeAccelerometer = exports.Sample = void 0;
var events_1 = require("events");
var fs = require("fs");
var readline = require("readline");
var WaitDuration = /** @class */ (function () {
    function WaitDuration(duration) {
        this._duration = duration;
    }
    Object.defineProperty(WaitDuration.prototype, "duration", {
        get: function () {
            return this._duration;
        },
        enumerable: false,
        configurable: true
    });
    return WaitDuration;
}());
var Sample = /** @class */ (function () {
    function Sample(x, y, z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
    Object.defineProperty(Sample.prototype, "X", {
        get: function () {
            return this.x;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sample.prototype, "Y", {
        get: function () {
            return this.y;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sample.prototype, "Z", {
        get: function () {
            return this.z;
        },
        enumerable: false,
        configurable: true
    });
    Sample.prototype.toArray = function () {
        return [this.X, this.Y, this.Z];
    };
    Sample.fromArray = function (from) {
        return new Sample(from[0], from[1], from[2]);
    };
    return Sample;
}());
exports.Sample = Sample;
var FakeAccelerometer = /** @class */ (function (_super) {
    __extends(FakeAccelerometer, _super);
    function FakeAccelerometer(flipRecording, doLoop, defaultSampleRate) {
        if (doLoop === void 0) { doLoop = true; }
        if (defaultSampleRate === void 0) { defaultSampleRate = 1000; }
        var _this = _super.call(this) || this;
        _this.defaultSampleRate = defaultSampleRate;
        _this.movementSensorRecording = flipRecording;
        _this.samples = new Set();
        _this.doLoop = doLoop;
        _this.doRun = false;
        return _this;
    }
    FakeAccelerometer.parseSample = function (sample) {
        var columns = sample.split(',');
        return new Sample(parseInt(columns[0]), parseInt(columns[1]), parseInt(columns[2]));
    };
    FakeAccelerometer.prototype.setupReader = function () {
        var _this = this;
        this.readStream = fs.createReadStream(this.movementSensorRecording);
        this.reader = readline.createInterface({
            input: this.readStream,
        });
        this.reader.on('line', function (line) {
            var columns = line.split(',');
            if (columns.length === 3) {
                // 3-axis accelerometer data
                _this.samples = _this.samples.add(FakeAccelerometer.parseSample(line));
            }
            else if (columns.length === 1) {
                // Wait time
                _this.samples = _this.samples.add(new WaitDuration(parseInt(columns[0])));
            }
            else {
                console.log("Unknown sample received: '" + line + "'.");
            }
        });
        this.reader.on('close', function () {
            if (_this.reader) {
                _this.reader.close();
            }
            if (_this.readStream) {
                _this.readStream.close();
            }
            // Start sending data
            return _this.emitSamples();
        });
    };
    FakeAccelerometer.prototype.emitSamples = function () {
        return __awaiter(this, void 0, void 0, function () {
            var it_1, done, _loop_1, this_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        it_1 = this.samples.entries();
                        done = false;
                        _loop_1 = function () {
                            var next, entry_1;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        next = it_1.next();
                                        if (!(!next.done && this_1.doRun)) return [3 /*break*/, 5];
                                        entry_1 = next.value[0];
                                        if (!(entry_1 instanceof Sample)) return [3 /*break*/, 2];
                                        this_1.emit('data', Date.now(), entry_1.toArray());
                                        return [4 /*yield*/, new Promise(function (resolve) {
                                                setTimeout(function () { return resolve(); }, _this.defaultSampleRate);
                                            })];
                                    case 1:
                                        _a.sent();
                                        return [3 /*break*/, 4];
                                    case 2:
                                        if (!(entry_1 instanceof WaitDuration)) return [3 /*break*/, 4];
                                        return [4 /*yield*/, new Promise(function (resolve) {
                                                setTimeout(function () { return resolve(); }, entry_1.duration);
                                            })];
                                    case 3:
                                        _a.sent();
                                        _a.label = 4;
                                    case 4: return [3 /*break*/, 6];
                                    case 5:
                                        done = true;
                                        _a.label = 6;
                                    case 6: return [2 /*return*/];
                                }
                            });
                        };
                        this_1 = this;
                        _a.label = 1;
                    case 1:
                        if (!!done) return [3 /*break*/, 3];
                        return [5 /*yield**/, _loop_1()];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 1];
                    case 3:
                        if (this.doRun && this.doLoop) return [3 /*break*/, 0];
                        _a.label = 4;
                    case 4:
                        this.emit('stopped');
                        return [2 /*return*/];
                }
            });
        });
    };
    FakeAccelerometer.prototype.start = function () {
        return __awaiter(this, void 0, void 0, function () {
            var fileExists;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.doRun = true;
                        return [4 /*yield*/, new Promise(function (resolve) {
                                return fs.exists(_this.movementSensorRecording, resolve);
                            })];
                    case 1:
                        fileExists = _a.sent();
                        if (!fileExists) {
                            throw new Error("Movement sensor recording with filename '" + this.movementSensorRecording + "' does not exist.");
                        }
                        this.setupReader();
                        return [2 /*return*/];
                }
            });
        });
    };
    FakeAccelerometer.prototype.stop = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.doRun = false;
                return [2 /*return*/];
            });
        });
    };
    FakeAccelerometer.prototype.isStarted = function () {
        return this.doRun;
    };
    return FakeAccelerometer;
}(events_1.EventEmitter));
exports.FakeAccelerometer = FakeAccelerometer;
