"use strict";
const toml = require('toml');
const os = require('os');
const fs = require('fs');
const { validateNoExtraPermissionsForOthersSync, generateChecksum } = require('../file_util');
const path = require('path');
const Logger = require('../logger').default;
const AuthenticationTypes = require('../authentication/authentication_types');
const Util = require('../util');
const { normalizeConnectionOptions } = require('../connection/normalize_connection_options');
function defaultIfNotSet(value, defaultValue) {
    if (value === null || typeof value === 'undefined' || value === '') {
        return defaultValue;
    }
    else {
        return value;
    }
}
function shouldReadTokenFromFile(fixedConfiguration) {
    return (fixedConfiguration &&
        fixedConfiguration.authenticator &&
        fixedConfiguration.authenticator.toUpperCase() === AuthenticationTypes.OAUTH_AUTHENTICATOR &&
        !Util.string.isNotNullOrEmpty(fixedConfiguration.token));
}
function readTokenFromFile(fixedConfiguration) {
    const tokenFilePath = fixedConfiguration.token_file_path
        ? fixedConfiguration.token_file_path
        : '/snowflake/session/token';
    const resolvedPath = fs.realpathSync(tokenFilePath);
    Logger().trace('Token file path is : %s', tokenFilePath);
    validateNoExtraPermissionsForOthersSync(resolvedPath);
    fixedConfiguration.token = fs.readFileSync(resolvedPath, 'utf-8').trim();
    if (!fixedConfiguration.token) {
        Logger().error('The token does not exist or has empty value.');
        throw new Error('The token does not exist or has empty value');
    }
    const tokenChecksum = generateChecksum(fixedConfiguration.token);
    Logger().info('Token used in connection has been read from file: %s. Checksum: %s', resolvedPath, tokenChecksum);
}
function loadConnectionConfiguration() {
    Logger().trace('Loading connection configuration from the local files...');
    const snowflakeConfigDir = defaultIfNotSet(process.env.SNOWFLAKE_HOME, path.join(os.homedir(), '.snowflake'));
    Logger().trace('Looking for connection file in directory %s', snowflakeConfigDir);
    const filePath = path.join(snowflakeConfigDir, 'connections.toml');
    const resolvedPath = fs.realpathSync(filePath);
    Logger().trace('Connection configuration file found under the path %s. Validating file access.', resolvedPath);
    validateNoExtraPermissionsForOthersSync(resolvedPath);
    const str = fs.readFileSync(resolvedPath, { encoding: 'utf8' });
    const configurationChecksum = generateChecksum(str);
    Logger().info('Connection configuration file is read from path: %s. Checksum: %s', resolvedPath, configurationChecksum);
    Logger().trace('Trying to parse the config file');
    const parsingResult = toml.parse(str);
    const configurationName = defaultIfNotSet(process.env.SNOWFLAKE_DEFAULT_CONNECTION_NAME, 'default');
    if (parsingResult[configurationName] !== undefined) {
        const configuration = parsingResult[configurationName];
        if (shouldReadTokenFromFile(configuration)) {
            Logger().info('Trying to read token from config file.');
            readTokenFromFile(configuration);
        }
        return normalizeConnectionOptions(configuration);
    }
    else {
        Logger().error('Connection configuration with name %s does not exist in the file %s', configurationName, resolvedPath);
        throw new Error(`Connection configuration with name ${configurationName} does not exist`);
    }
}
exports.loadConnectionConfiguration = loadConnectionConfiguration;
//# sourceMappingURL=connection_configuration.js.map