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());
    });
};
export function withColIndex(result) {
    const index = result.headers.reduce((acc, column, index) => {
        acc[column] = index;
        return acc;
    }, {});
    return Object.assign(Object.assign({}, result), { index });
}
export const toListOfObjects = ({ rows, headers, }) => {
    return rows.map((row) => {
        const obj = {};
        row.forEach((value, index) => {
            const key = headers[index];
            obj[key] = value;
        });
        return obj;
    });
};
export const entityToArray = (obj, columns) => {
    return `[${columns
        .map((col) => {
        const key = col.column;
        const value = obj[key];
        return col.type === 'Json'
            ? `parse_json('${JSON.stringify(value)}')`
            : col.type === 'String'
                ? `"${value}"`
                : value;
    })
        .join(', ')}]`;
};
export const snakeToCamel = (str) => str.replace(/([-_][a-z])/g, (group) => group.toUpperCase().replace('-', '').replace('_', ''));
export const camelToSnake = (str) => str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
export function transformToDto(dbEntity) {
    const dto = {};
    for (const key in dbEntity) {
        const camelCaseKey = snakeToCamel(key);
        dto[camelCaseKey] = dbEntity[key];
    }
    return dto;
}
export function transformToDbEntity(dto) {
    const dbEntity = {};
    for (const key in dto) {
        const snakeCaseKey = camelToSnake(key);
        dbEntity[snakeCaseKey] = dto[key];
    }
    return dbEntity;
}
export function transformListToDbEntity(array) {
    return array.map((dto) => transformToDbEntity(dto));
}
export function transformListToDto(array) {
    return array.map((dto) => transformToDto(dto));
}
export function removeUndefinedFields(entity) {
    Object.keys(entity).forEach((key) => {
        if (entity[key] === undefined) {
            delete entity[key];
        }
    });
    return entity;
}
export const dbResultToDtoList = (dbResult) => {
    if (!dbResult.ok) {
        throw new Error(`Can't parse DBResult: ${dbResult === null || dbResult === void 0 ? void 0 : dbResult.message}`);
    }
    const { headers, rows } = dbResult;
    const camelCaseHeadersMap = headers.reduce((acc, header) => {
        acc[header] = snakeToCamel(header);
        return acc;
    }, {});
    return rows.map((row) => {
        const obj = {};
        headers.forEach((header, index) => {
            obj[camelCaseHeadersMap[header]] = row[index];
        });
        return obj;
    });
};
export function jsonifyFields(obj, fields) {
    Object.keys(obj).forEach((k) => {
        if (fields.includes(k)) {
            if (obj[k]) {
                try {
                    obj[k] = JSON.parse(obj[k]);
                }
                catch (_a) { }
            }
        }
    });
    return obj;
}
export function clearIndexedDBStore(dbName, storeName) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(dbName);
            request.onerror = (event) => {
                var _a;
                reject(`Database error: ${(_a = request.error) === null || _a === void 0 ? void 0 : _a.message}`);
            };
            request.onsuccess = (event) => {
                const db = request.result;
                const transaction = db.transaction(storeName, 'readwrite');
                const store = transaction.objectStore(storeName);
                const clearRequest = store.clear();
                clearRequest.onsuccess = () => {
                    console.log(`Store cleared ${dbName}/${storeName}`);
                    resolve();
                };
                clearRequest.onerror = () => {
                    var _a;
                    reject(`Error clearing the store: ${(_a = clearRequest.error) === null || _a === void 0 ? void 0 : _a.message}`);
                };
                transaction.oncomplete = () => {
                    db.close();
                };
            };
        });
    });
}
//# sourceMappingURL=utils.js.map