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 };
    }
};
import '../generated/service-container-extension';
import { StepOperations } from '@iotize/common/task-manager';
import { sleep } from '@iotize/common/utility';
import { TapError } from '@iotize/tap';
import { ResultCode } from '@iotize/tap/client/api';
import { CRC } from '@iotize/tap/client/impl';
import { SinglePacketChunk } from '../generated/models';
import { debug } from '../logger';
import { SinglePacketError } from './definitions';
import { SinglePacketBuilder } from './single-packet-builder';
import { SinglePacketSplitter } from './single-packet-splitter';
var SinglePacketStoreLoader = /** @class */ (function (_super) {
    __extends(SinglePacketStoreLoader, _super);
    function SinglePacketStoreLoader(steps, 
    // public readonly crc: number,
    singlePacketService) {
        var _this = _super.call(this, StepOperations.createSequentialContainers(steps)) || this;
        _this.singlePacketService = singlePacketService;
        return _this;
    }
    SinglePacketStoreLoader.createOperationsFromBytes = function (data, singlePacketService, options) {
        var chunkSize = (options === null || options === void 0 ? void 0 : options.chunkSize) || SinglePacketBuilder.MAX_PART_SIZE;
        var offsetFitsOn2Bytes = (data.length / chunkSize) <= 0xFFFF;
        var singlePacketSplitter = new SinglePacketSplitter({
            chunkSize: chunkSize,
            format: offsetFitsOn2Bytes ? SinglePacketChunk.Format.OFFSET_ON_2_BYTES : SinglePacketChunk.Format.OFFSET_ON_4_BYTES,
            pad: (options && 'pad' in options) ? options.pad : true
        });
        var packets = singlePacketSplitter.chunk(data);
        return SinglePacketStoreLoader.createOperationsFromChunk(packets, singlePacketService, options);
    };
    SinglePacketStoreLoader.createFromBytes = function (data, singlePacketService, options) {
        var steps = SinglePacketStoreLoader.createOperationsFromBytes(data, singlePacketService, options);
        return new SinglePacketStoreLoader(steps, 
        // expectedCRC,
        singlePacketService);
    };
    /**
     * Create single packet loading operations
     * @param packets Single packet chunks to load to the Tap
     * @param expectedCRC expected CRC sent to the Tap when executing the single packet. if you don't plan to execute single packet, you pass a dummy value
     * @param singlePacketService
     * @param options
     */
    SinglePacketStoreLoader.createOperationsFromChunk = function (packets, singlePacketService, options, output) {
        var _this = this;
        if (output === void 0) { output = {
            expectedCRC: 0
        }; }
        output.expectedCRC = CRC.FIRST_VALUE;
        var operations = packets
            .map(function (packet, index) {
            return function (observer, context) { return __awaiter(_this, void 0, void 0, function () {
                var retryCount, maxRetry, response;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (packet.data.length > SinglePacketBuilder.MAX_PART_SIZE) {
                                throw SinglePacketError.maxSinglePacketPartSizeExceeded(packet, SinglePacketBuilder.MAX_PART_SIZE);
                            }
                            debug('createSinglePacketLoadOperations', "sendSinglePacket", "sending packet " + (index + 1) + "/" + packets.length + " offset: " + packet.offset + "..." + (packet.offset + (packet.length || 0)));
                            retryCount = 0;
                            maxRetry = (options === null || options === void 0 ? void 0 : options.maxRetry) || 3;
                            output.expectedCRC = CRC.fromBytes(packet.data, output.expectedCRC);
                            _a.label = 1;
                        case 1:
                            if (!true) return [3 /*break*/, 5];
                            retryCount++;
                            return [4 /*yield*/, singlePacketService.writeChunk(packet)];
                        case 2:
                            response = _a.sent();
                            if (!(retryCount < maxRetry &&
                                (response.status === ResultCode.SERVICE_UNAVAILABLE
                                    || response.status === ResultCode.NVM_ERROR))) return [3 /*break*/, 4];
                            debug('createSinglePacketLoadOperations', "Attempt " + (retryCount + 1) + "/" + maxRetry + " failed with error " + TapError.reponseStatusError(response).toString());
                            return [4 /*yield*/, sleep((options === null || options === void 0 ? void 0 : options.retryDelay) || 500)];
                        case 3:
                            _a.sent();
                            return [3 /*break*/, 1];
                        case 4:
                            response.successful();
                            observer.next({
                                step: SinglePacketStoreLoader.Step.loadPacketChunk,
                                progress: {
                                    total: packets.length,
                                    loaded: index + 1
                                }
                            });
                            return [2 /*return*/];
                        case 5: return [2 /*return*/];
                    }
                });
            }); };
        });
        if (options === null || options === void 0 ? void 0 : options.execute) {
            operations.push(function (observer, context) { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            observer.next({
                                step: SinglePacketStoreLoader.Step.executeSinglePacket,
                                expectedCRC: output.expectedCRC
                            });
                            return [4 /*yield*/, singlePacketService.executeSinglePacketInStore(output.expectedCRC)];
                        case 1:
                            (_a.sent()).successful();
                            return [2 /*return*/];
                    }
                });
            }); });
        }
        return operations;
    };
    SinglePacketStoreLoader.createFromChunks = function (packets, singlePacketService, options) {
        return new SinglePacketStoreLoader(SinglePacketStoreLoader.createOperationsFromChunk(packets, singlePacketService, options), singlePacketService);
    };
    SinglePacketStoreLoader.computeCRC = function (data) {
        if (data instanceof Uint8Array) {
            return CRC.mpeg2().compute(data);
        }
        else {
            return data.reduce(function (crc, packet) {
                return CRC.mpeg2().compute(packet.data, crc);
            }, CRC.FIRST_VALUE);
        }
    };
    return SinglePacketStoreLoader;
}(StepOperations));
export { SinglePacketStoreLoader };
(function (SinglePacketStoreLoader) {
    var Step;
    (function (Step) {
        Step["loadPacketChunk"] = "loadPacketChunk";
        Step["executeSinglePacket"] = "executeSinglePacket";
    })(Step = SinglePacketStoreLoader.Step || (SinglePacketStoreLoader.Step = {}));
})(SinglePacketStoreLoader || (SinglePacketStoreLoader = {}));
//# sourceMappingURL=data:application/json;base64, 