"use strict";
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCollectionSize = exports.makeCollectionFromFileList = exports.assertCollection = exports.isCollection = void 0;
const error_1 = require("./error");
const file_1 = require("./file");
const type_1 = require("./type");
function isCollection(data) {
    if (!Array.isArray(data)) {
        return false;
    }
    return data.every(entry => typeof entry === 'object' && entry.data && entry.path && (0, type_1.isUint8Array)(entry.data));
}
exports.isCollection = isCollection;
function assertCollection(data) {
    if (!isCollection(data)) {
        throw new error_1.BeeArgumentError('invalid collection', data);
    }
}
exports.assertCollection = assertCollection;
function makeFilePath(file) {
    if (file.webkitRelativePath && file.webkitRelativePath !== '') {
        return file.webkitRelativePath.replace(/.*?\//i, '');
    }
    if (file.name) {
        return file.name;
    }
    throw new TypeError('file is not valid File object');
}
function makeCollectionFromFileList(fileList) {
    return __awaiter(this, void 0, void 0, function* () {
        const collection = [];
        for (let i = 0; i < fileList.length; i++) {
            const file = fileList[i];
            if (file) {
                collection.push({
                    path: makeFilePath(file),
                    data: new Uint8Array(yield (0, file_1.fileArrayBuffer)(file)),
                });
            }
        }
        return collection;
    });
}
exports.makeCollectionFromFileList = makeCollectionFromFileList;
/**
 * Calculate cumulative size of files
 *
 * @param fileList list of files to check
 * @returns size in bytes
 */
function getCollectionSize(fileList) {
    let sum = 0;
    for (let i = 0; i < fileList.length; i++) {
        const file = fileList[i];
        if (file) {
            sum += file.size;
        }
    }
    return sum;
}
exports.getCollectionSize = getCollectionSize;
