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 __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 { takeEvery, call, put, select, fork } from 'redux-saga/effects';
import { updateCode as updateCodeAction } from '../actions/software';
import { showNotification, hideNotification } from '../actions/ui';
import { undo as undoThreed, redo as redoThreed, selectObject, updateObject, updateObjectViewOption, } from '../actions/threed';
import { generateArduinoCode } from '../lib/code-generation';
import web2board, { ConnectionError, CompileError, BoardNotDetectedError, } from '../lib/web2board';
import Object3D from '../lib/object3dts/Object3D';
var delay = function (ms) { return new Promise(function (res) { return setTimeout(res, ms); }); };
function updateCode() {
    var bloqs, hardware;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, select(function (state) { return state.software.bloqs; })];
            case 1:
                bloqs = _a.sent();
                return [4 /*yield*/, select(function (state) { return state.hardware; })];
            case 2:
                hardware = _a.sent();
                return [4 /*yield*/, put(updateCodeAction(generateArduinoCode(bloqs, hardware)))];
            case 3:
                _a.sent();
                return [2 /*return*/];
        }
    });
}
function uploadCode() {
    var code, uploadGen, _a, reply, done, fn, e_1;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4 /*yield*/, select(function (state) { return state.software.code; })];
            case 1:
                code = _b.sent();
                _b.label = 2;
            case 2:
                _b.trys.push([2, 16, , 25]);
                uploadGen = web2board.upload(code);
                _b.label = 3;
            case 3:
                if (!true) return [3 /*break*/, 15];
                return [4 /*yield*/, call([uploadGen, uploadGen.next])];
            case 4:
                _a = _b.sent(), reply = _a.value, done = _a.done;
                fn = reply['function'];
                if (!(fn === 'is_compiling')) return [3 /*break*/, 6];
                return [4 /*yield*/, put(showNotification('compiling', 'Compiling'))];
            case 5:
                _b.sent();
                return [3 /*break*/, 8];
            case 6: return [4 /*yield*/, put(hideNotification('compiling'))];
            case 7:
                _b.sent();
                _b.label = 8;
            case 8:
                if (!(fn === 'is_uploading')) return [3 /*break*/, 10];
                return [4 /*yield*/, put(showNotification('uploading', 'Uploading'))];
            case 9:
                _b.sent();
                return [3 /*break*/, 12];
            case 10: return [4 /*yield*/, put(hideNotification('uploading'))];
            case 11:
                _b.sent();
                _b.label = 12;
            case 12:
                if (!done) return [3 /*break*/, 14];
                return [4 /*yield*/, put(showNotification('w2b_success', 'Uploaded!', 5000))];
            case 13:
                _b.sent();
                return [2 /*return*/];
            case 14: return [3 /*break*/, 3];
            case 15: return [3 /*break*/, 25];
            case 16:
                e_1 = _b.sent();
                return [4 /*yield*/, put(hideNotification('compiling'))];
            case 17:
                _b.sent();
                return [4 /*yield*/, put(hideNotification('uploading'))];
            case 18:
                _b.sent();
                if (!(e_1 instanceof ConnectionError)) return [3 /*break*/, 20];
                return [4 /*yield*/, put(showNotification('w2b_error', 'Could not connect to Web2Board', 5000))];
            case 19:
                _b.sent();
                _b.label = 20;
            case 20:
                if (!(e_1 instanceof BoardNotDetectedError)) return [3 /*break*/, 22];
                return [4 /*yield*/, put(showNotification('w2b_error', 'Board not detected', 5000))];
            case 21:
                _b.sent();
                _b.label = 22;
            case 22:
                if (!(e_1 instanceof CompileError)) return [3 /*break*/, 24];
                return [4 /*yield*/, put(showNotification('w2b_error', 'Error compiling', 5000))];
            case 23:
                _b.sent();
                _b.label = 24;
            case 24: return [3 /*break*/, 25];
            case 25: return [2 /*return*/];
        }
    });
}
function watchNotificationTime(_a) {
    var _b = _a.payload, key = _b.key, time = _b.time;
    return __generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                if (!time) return [3 /*break*/, 3];
                return [4 /*yield*/, call(delay, time)];
            case 1:
                _c.sent();
                return [4 /*yield*/, put(hideNotification(key))];
            case 2:
                _c.sent();
                _c.label = 3;
            case 3: return [2 /*return*/];
        }
    });
}
function watchKeyDown(_a) {
    var shiftPressed, controlPressed, threedPast, threedFuture;
    var key = _a.payload;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4 /*yield*/, select(function (state) { return state.ui.shiftPressed; })];
            case 1:
                shiftPressed = _b.sent();
                return [4 /*yield*/, select(function (state) { return state.ui.controlPressed; })];
            case 2:
                controlPressed = _b.sent();
                return [4 /*yield*/, select(function (state) { return state.threed.scene.past; })];
            case 3:
                threedPast = _b.sent();
                return [4 /*yield*/, select(function (state) { return state.threed.scene.future; })];
            case 4:
                threedFuture = _b.sent();
                if (!(key === 'z' && controlPressed && threedPast.length)) return [3 /*break*/, 6];
                return [4 /*yield*/, put(undoThreed())];
            case 5:
                _b.sent();
                _b.label = 6;
            case 6:
                if (!(key === 'Z' && controlPressed && threedFuture.length)) return [3 /*break*/, 8];
                return [4 /*yield*/, put(redoThreed())];
            case 7:
                _b.sent();
                _b.label = 8;
            case 8: return [2 /*return*/];
        }
    });
}
function watchCreateObject() {
    var objects;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, select(function (state) { return state.threed.scene.objects; })];
            case 1:
                objects = _a.sent();
                return [4 /*yield*/, put(selectObject(objects[objects.length - 1]))];
            case 2:
                _a.sent();
                return [2 /*return*/];
        }
    });
}
function convertToBasicOperations(object, scene) {
    var _a, position, angle, scale;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0: return [4 /*yield*/, call([scene, scene.getPositionAsync], object)];
            case 1:
                _a = _b.sent(), position = _a.position, angle = _a.angle, scale = _a.scale;
                return [4 /*yield*/, put(updateObject(__assign({}, object, { operations: [
                            Object3D.createTranslateOperation(position.x, position.y, position.z),
                            Object3D.createRotateOperation(angle.x, angle.y, angle.z),
                            Object3D.createScaleOperation(scale.x, scale.y, scale.z),
                        ] })))];
            case 2:
                _b.sent();
                return [2 /*return*/];
        }
    });
}
function convertToAdvancedOperations(object, scene) {
    var operations;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                operations = [];
                object.operations.forEach(function (operation) {
                    if (operation.type === 'translation') {
                        if (operation.x !== 0 || operation.y !== 0 || operation.z !== 0) {
                            operations.push(operation);
                        }
                    }
                    if (operation.type === 'rotation') {
                        if (operation.x !== 0) {
                            operations.push(Object3D.createRotateOperation(operation.x, 0, 0));
                        }
                        if (operation.y !== 0) {
                            operations.push(Object3D.createRotateOperation(0, operation.y, 0));
                        }
                        if (operation.z !== 0) {
                            operations.push(Object3D.createRotateOperation(0, 0, operation.z));
                        }
                    }
                    if (operation.type === 'scale') {
                        if (operation.x !== 1 || operation.y !== 1 || operation.z !== 1) {
                            operations.push(operation);
                        }
                    }
                });
                return [4 /*yield*/, put(updateObject(__assign({}, object, { operations: operations })))];
            case 1:
                _a.sent();
                return [2 /*return*/];
        }
    });
}
function watchSetAdvancedMode(_a) {
    var scene, objects, _i, objects_1, object;
    var isAdvanced = _a.payload;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                sessionStorage.setItem('advancedMode', JSON.stringify(isAdvanced));
                return [4 /*yield*/, select(function (state) { return state.threed.scene.sceneInstance; })];
            case 1:
                scene = _b.sent();
                return [4 /*yield*/, select(function (state) { return state.threed.scene.objects; })];
            case 2:
                objects = _b.sent();
                _i = 0, objects_1 = objects;
                _b.label = 3;
            case 3:
                if (!(_i < objects_1.length)) return [3 /*break*/, 8];
                object = objects_1[_i];
                if (!isAdvanced) return [3 /*break*/, 5];
                return [4 /*yield*/, fork(convertToAdvancedOperations, object, scene)];
            case 4:
                _b.sent();
                return [3 /*break*/, 7];
            case 5: return [4 /*yield*/, fork(convertToBasicOperations, object, scene)];
            case 6:
                _b.sent();
                _b.label = 7;
            case 7:
                _i++;
                return [3 /*break*/, 3];
            case 8: return [2 /*return*/];
        }
    });
}
function isDescendant(object, id) {
    if (object.id === id)
        return true;
    var _a = object.children, children = _a === void 0 ? [] : _a;
    return children.some(function (child) { return isDescendant(child, id); });
}
function watchSelectedObjects() {
    var scene, objects, selectedIds, _loop_1, _i, objects_2, object;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, select(function (state) { return state.threed.scene.sceneInstance; })];
            case 1:
                scene = _a.sent();
                return [4 /*yield*/, select(function (state) { return state.threed.scene.objects; })];
            case 2:
                objects = _a.sent();
                return [4 /*yield*/, select(function (state) { return state.threed.ui.selectedIds; })];
            case 3:
                selectedIds = _a.sent();
                _loop_1 = function (object) {
                    var opacity;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                opacity = 1;
                                if (selectedIds.length > 0) {
                                    opacity = selectedIds.some(function (id) { return isDescendant(object, id); }) ? 1 : 0.5;
                                }
                                return [4 /*yield*/, put(updateObjectViewOption(object, 'opacity', opacity))];
                            case 1:
                                _a.sent();
                                return [2 /*return*/];
                        }
                    });
                };
                _i = 0, objects_2 = objects;
                _a.label = 4;
            case 4:
                if (!(_i < objects_2.length)) return [3 /*break*/, 7];
                object = objects_2[_i];
                return [5 /*yield**/, _loop_1(object)];
            case 5:
                _a.sent();
                _a.label = 6;
            case 6:
                _i++;
                return [3 /*break*/, 4];
            case 7: return [2 /*return*/];
        }
    });
}
function rootSaga() {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, takeEvery('SOFTWARE_UPDATE_BLOQS', updateCode)];
            case 1:
                _a.sent();
                return [4 /*yield*/, takeEvery('SOFTWARE_UPLOAD_CODE', uploadCode)];
            case 2:
                _a.sent();
                return [4 /*yield*/, takeEvery('UI_SHOW_NOTIFICATION', watchNotificationTime)];
            case 3:
                _a.sent();
                return [4 /*yield*/, takeEvery('UI_KEY_DOWN', watchKeyDown)];
            case 4:
                _a.sent();
                return [4 /*yield*/, takeEvery('THREED_CREATE_OBJECT', watchCreateObject)];
            case 5:
                _a.sent();
                return [4 /*yield*/, takeEvery('THREED_SET_ADVANCED_MODE', watchSetAdvancedMode)];
            case 6:
                _a.sent();
                return [4 /*yield*/, takeEvery('THREED_SELECT_OBJECT', watchSelectedObjects)];
            case 7:
                _a.sent();
                return [4 /*yield*/, takeEvery('THREED_DESELECT_OBJECT', watchSelectedObjects)];
            case 8:
                _a.sent();
                return [4 /*yield*/, takeEvery('THREED_DESELECT_ALL_OBJECTS', watchSelectedObjects)];
            case 9:
                _a.sent();
                return [2 /*return*/];
        }
    });
}
export default rootSaga;
//# sourceMappingURL=index.js.map