import fdb


class MedicusDB:

    def __init__(self, host, db_path, user="SYSDBA", password="masterkey", charset="WIN1250"):
        self.conn = fdb.connect(
            host=host,
            database=db_path,
            user=user,
            password=password,
            charset=charset
        )
        self.cur = self.conn.cursor()

    def query(self, sql, params=None):
        self.cur.execute(sql, params or ())
        return self.cur.fetchall()

    def query_dict(self, sql, params=None):
        self.cur.execute(sql, params or ())
        cols = [d[0].strip().lower() for d in self.cur.description]
        return [dict(zip(cols, row)) for row in self.cur.fetchall()]

    def get_active_registered_patients(self, as_dict=False):
        sql = """
        SELECT
            kar.rodcis,
            kar.prijmeni,
            kar.jmeno,
            kar.poj
        FROM registr
        JOIN kar ON registr.idpac = kar.idpac
        WHERE registr.datum_zruseni IS NULL
          AND registr.priznak IN ('A','D','V')
          AND kar.rodcis IS NOT NULL
          AND kar.rodcis <> ''
          AND kar.vyrazen <> 'A'
        """
        if as_dict:
            return self.query_dict(sql)
        return self.query(sql)

    def get_all_patients(self, as_dict=False):
        sql = """
        SELECT
            kar.rodcis,
            kar.prijmeni,
            kar.jmeno,
            kar.poj
        FROM kar
        """
        if as_dict:
            return self.query_dict(sql)
        return self.query(sql)

    def close(self):
        self.conn.close()
