""" This script loads and exports connection params.
"""
import os
from typing import Optional


class Params:
    """
    Represents database connection parameters and provides a method to generate a formatted
    connection string compatible with PostgreSQL.
    """
    connection_title: str  # Name of the connection file
    db_name: str
    db_host: str
    db_port: str
    username: str
    password: str

    def __init__(
        self,
        connection_title: str,
        db_name: str,
        db_host: str,
        db_port: str,
        username: str,
        password: str
    ):
        self.connection_title = connection_title
        self.db_name = db_name
        self.db_host = db_host
        self.db_port = db_port
        self.username = username
        self.password = password

    def connection_string(self) -> str:
        """ Returns a connection string compatible with PostgreSQL."""
        return f'postgres://{self.username}:{self.password}@{self.db_host}:{self.db_port}/{self.db_name}'


# Load params
parameter_sets: list[Params] = list()

script_path = os.path.dirname(__file__)
rel_path = 'connection_params/'
params_dir = os.path.join(script_path, rel_path)
for param_file in os.listdir(params_dir):
    try:
        with open(os.path.join(params_dir, param_file)) as f:
            flines = f.readlines()
            param = Params(
                param_file,
                db_name = flines[0].strip(),
                db_host = flines[3].strip(),
                db_port = flines[4].strip(),
                username = flines[1].strip(),
                password = flines[2].strip()
            )
            if len(flines) > 5:
                raise ValueError('Malformed database connection parameters file.')

            parameter_sets.append(param)
    except (KeyError, IndexError):
        print('Invalid connection parameters file.')
        pass

# Set params to find easily

# Test
local_docker_init: Optional[Params] = None
local_docker_dev: Optional[Params] = None
local_docker_pub: Optional[Params] = None

# Production
chemrecon_dev: Optional[Params] = None
chemrecon_pub: Optional[Params] = None

for p in parameter_sets:
    match p.connection_title:
        case 'local_docker_init.dbinfo':
            local_docker_init = p
        case 'local_docker_dev.dbinfo':
            local_docker_dev = p
        case 'local_docker_pub.dbinfo':
            local_docker_pub = p
        case 'chemrecon_dev.dbinfo':
            chemrecon_dev = p
        case 'chemrecon_pub.dbinfo':
            chemrecon_pub = p
