"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = createDbFromSchema;
const fs_1 = __importDefault(require("fs"));
const noDatabaseDbHandler_1 = __importDefault(require("../utils/noDatabaseDbHandler"));
const varDatabaseDbHandler_1 = __importDefault(require("../utils/varDatabaseDbHandler"));
const createTable_1 = __importDefault(require("../utils/createTable"));
const updateTable_1 = __importDefault(require("../utils/updateTable"));
const dbHandler_1 = __importDefault(require("../utils/dbHandler"));
const ejson_1 = __importDefault(require("../../utils/ejson"));
const grab_dir_names_1 = __importDefault(require("../../utils/backend/names/grab-dir-names"));
const check_db_record_1 = __importDefault(require("./check-db-record"));
const check_table_record_1 = __importDefault(require("./check-table-record"));
const handle_indexes_1 = __importDefault(require("./handle-indexes"));
/**
 * # Create database from Schema Function
 * @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
 */
function createDbFromSchema(_a) {
    return __awaiter(this, arguments, void 0, function* ({ userId, targetDatabase, dbSchemaData, }) {
        var _b, _c;
        const { userSchemaMainJSONFilePath, mainShemaJSONFilePath } = (0, grab_dir_names_1.default)({
            userId,
        });
        const schemaPath = userSchemaMainJSONFilePath || mainShemaJSONFilePath;
        const dbSchema = dbSchemaData ||
            ejson_1.default.parse(fs_1.default.readFileSync(schemaPath, "utf8"));
        if (!dbSchema) {
            console.log("Schema Not Found!");
            return false;
        }
        for (let i = 0; i < dbSchema.length; i++) {
            const database = dbSchema[i];
            const { dbFullName, tables, dbSlug, childrenDatabases } = database;
            if (targetDatabase && dbFullName != targetDatabase) {
                continue;
            }
            const dbCheck = yield (0, noDatabaseDbHandler_1.default)(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`);
            if (!((_b = dbCheck === null || dbCheck === void 0 ? void 0 : dbCheck[0]) === null || _b === void 0 ? void 0 : _b.dbFullName)) {
                const newDatabase = yield (0, noDatabaseDbHandler_1.default)(`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
            }
            const allTables = yield (0, noDatabaseDbHandler_1.default)(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`);
            let recordedDbEntry = yield (0, check_db_record_1.default)({
                dbSchema: database,
                userId,
            });
            for (let tb = 0; tb < allTables.length; tb++) {
                const { TABLE_NAME } = allTables[tb];
                /**
                 * @description Check if TABLE_NAME is part of the tables contained
                 * in the user schema JSON. If it's not, the table is either deleted
                 * or the table name has been recently changed
                 */
                if (!tables.filter((_table) => _table.tableName === TABLE_NAME)[0]) {
                    const oldTableFilteredArray = tables.filter((_table) => _table.tableNameOld &&
                        _table.tableNameOld === TABLE_NAME);
                    /**
                     * @description Check if this table has been recently renamed. Rename
                     * table id true. Drop table if false
                     */
                    if (oldTableFilteredArray && oldTableFilteredArray[0]) {
                        console.log("Renaming Table");
                        yield (0, varDatabaseDbHandler_1.default)({
                            queryString: `RENAME TABLE \`${dbFullName}\`.\`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
                        });
                    }
                    else {
                        console.log(`Dropping Table from ${dbFullName}`);
                        yield (0, varDatabaseDbHandler_1.default)({
                            queryString: `DROP TABLE \`${dbFullName}\`.\`${TABLE_NAME}\``,
                        });
                        const deleteTableEntry = yield (0, dbHandler_1.default)({
                            query: `DELETE FROM datasquirel.user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
                            values: [userId, dbSlug, TABLE_NAME],
                        });
                    }
                }
            }
            /**
             * @description Iterate through each table and perform table actions
             */
            for (let t = 0; t < tables.length; t++) {
                const table = tables[t];
                const { tableName, fields, indexes } = table;
                /**
                 * @description Check if table exists
                 * @type {any}
                 */
                const tableCheck = yield (0, varDatabaseDbHandler_1.default)({
                    queryString: `
                    SELECT EXISTS (
                        SELECT
                        TABLE_NAME
                        FROM
                        information_schema.TABLES
                        WHERE
                        TABLE_SCHEMA = ? AND
                        TABLE_NAME = ?
                        ) AS tableExists`,
                    queryValuesArray: [dbFullName, table.tableName],
                });
                ////////////////////////////////////////
                if (tableCheck && ((_c = tableCheck[0]) === null || _c === void 0 ? void 0 : _c.tableExists) > 0) {
                    /**
                     * @description Update table if table exists
                     */
                    const updateExistingTable = yield (0, updateTable_1.default)({
                        dbFullName: dbFullName,
                        tableName: tableName,
                        tableNameFull: table.tableFullName,
                        tableInfoArray: fields,
                        userId,
                        dbSchema,
                        tableIndexes: indexes,
                        tableIndex: t,
                        childDb: database.childDatabase || undefined,
                        recordedDbEntry,
                        tableSchema: table,
                    });
                    if (table.childrenTables && table.childrenTables[0]) {
                        for (let ch = 0; ch < table.childrenTables.length; ch++) {
                            const childTable = table.childrenTables[ch];
                            const updateExistingChildTable = yield (0, updateTable_1.default)({
                                dbFullName: childTable.dbNameFull,
                                tableName: childTable.tableName,
                                tableNameFull: childTable.tableNameFull,
                                tableInfoArray: fields,
                                userId,
                                dbSchema,
                                tableIndexes: indexes,
                                clone: true,
                                childDb: database.childDatabase || undefined,
                                recordedDbEntry,
                                tableSchema: table,
                            });
                        }
                    }
                }
                else {
                    /**
                     * @description Create new Table if table doesnt exist
                     */
                    const createNewTable = yield (0, createTable_1.default)({
                        tableName: tableName,
                        tableInfoArray: fields,
                        dbFullName: dbFullName,
                        tableSchema: table,
                        recordedDbEntry,
                    });
                    /**
                     * Handle DATASQUIREL Table Indexes
                     * ===================================================
                     * @description Iterate through each datasquirel schema
                     * table index(if available), and perform operations
                     */
                    if (indexes === null || indexes === void 0 ? void 0 : indexes[0]) {
                        (0, handle_indexes_1.default)({
                            dbFullName,
                            indexes,
                            tableName,
                        });
                    }
                }
                const tableRecord = yield (0, check_table_record_1.default)({
                    dbFullName,
                    dbSchema,
                    tableSchema: table,
                    dbRecord: recordedDbEntry,
                    userId,
                });
            }
            /**
             * @description Check all children databases
             */
            if (childrenDatabases === null || childrenDatabases === void 0 ? void 0 : childrenDatabases[0]) {
                for (let ch = 0; ch < childrenDatabases.length; ch++) {
                    const childDb = childrenDatabases[ch];
                    const { dbFullName } = childDb;
                    yield createDbFromSchema({
                        userId,
                        targetDatabase: dbFullName,
                    });
                }
            }
        }
        return true;
    });
}