import signal

from django.db.backends.base.client import BaseDatabaseClient


class DatabaseClient(BaseDatabaseClient):
    executable_name = 'psql'

    @classmethod
    def settings_to_cmd_args_env(cls, settings_dict, parameters):
        args = [cls.executable_name]
        options = settings_dict.get('OPTIONS', {})

        host = settings_dict.get('HOST')
        port = settings_dict.get('PORT')
        dbname = settings_dict.get('NAME') or 'postgres'
        user = settings_dict.get('USER')
        passwd = settings_dict.get('PASSWORD')
        sslmode = options.get('sslmode')
        sslrootcert = options.get('sslrootcert')
        sslcert = options.get('sslcert')
        sslkey = options.get('sslkey')

        if user:
            args += ['-U', user]
        if host:
            args += ['-h', host]
        if port:
            args += ['-p', str(port)]
        args += [dbname]
        args.extend(parameters)

        env = {}
        if passwd:
            env['PGPASSWORD'] = str(passwd)
        if sslmode:
            env['PGSSLMODE'] = str(sslmode)
        if sslrootcert:
            env['PGSSLROOTCERT'] = str(sslrootcert)
        if sslcert:
            env['PGSSLCERT'] = str(sslcert)
        if sslkey:
            env['PGSSLKEY'] = str(sslkey)
        return args, (env or None)

    def runshell(self, parameters):
        sigint_handler = signal.getsignal(signal.SIGINT)
        try:
            # Allow SIGINT to pass to psql to abort queries.
            signal.signal(signal.SIGINT, signal.SIG_IGN)
            super().runshell(parameters)
        finally:
            # Restore the original SIGINT handler.
            signal.signal(signal.SIGINT, sigint_handler)
