"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSettings = getSettings;
exports.default = default_1;
const Local_1 = require("../Local");
const URI_1 = require("../utils/URI");
const Local_2 = require("../Local");
const ramda_1 = require("ramda");
const promises_1 = require("node:fs/promises");
const Password_1 = __importDefault(require("../Password"));
function getSettings(settings) {
    return {
        columns: settings.columns.filter((0, ramda_1.whereEq)({ visible: true })).map(({ name, width }) => ({ name, width })),
        sort: settings.sort,
        history: settings.history,
        filter: settings.filter
    };
}
async function default_1(path, settings) {
    const content = (0, Local_2.stat)(path) ? await (0, Local_1.read)(path) : null;
    if ((0, Local_2.stat)(path) && !content) {
        throw new Error(`Cant read connection file: ${path} ${typeof content}`);
    }
    let config = content ? JSON.parse(content) : {};
    if ('scheme' in settings) {
        config = { ...config, ...(0, ramda_1.omit)(['password'], settings) };
        if (settings.password.length) {
            Password_1.default.save((0, URI_1.connectionID)(settings.scheme, settings.user, settings.host, settings.port), settings.password);
        }
    }
    else {
        if (settings.local) {
            config.local = getSettings(settings.local);
        }
        if (settings.remote) {
            config.remote = getSettings(settings.remote);
        }
        if (settings.path) {
            config.path = settings.path;
        }
        config.sync = settings.sync;
    }
    if (!config) {
        throw new Error(`Save invalid config into ${path}`);
    }
    await (0, promises_1.writeFile)(path, JSON.stringify(config));
}
