"""
Prints the database kontor structure
"""
import mariadb
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from config import get_database_cursors, get_logger

parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('--verbose', '-v', action='count', default=0)
args = parser.parse_args()


def show_tables(cur, log):
    """
    Retrieves the list of tables from the database
    :param cur:
    :param log:
    :return:
    """
    log.info('get list of tables')
    table_list = []
    cur.execute("SHOW TABLES")
    for (tablename,) in cur.fetchall():
        table_list.append(tablename)
    return table_list


def get_field_info(cur):
    """
    Retrieves the field info associated with a cursor
    :param cur:
    :return:
    """
    field_info = mariadb.fieldinfo()
    field_info_text_list = []
    for column in cur.description:
        column_name = column[0]
        column_type = field_info.type(column)
        column_flags = field_info.flag(column)
        field_info_text_list.append(f"{column_name}: {column_type} {column_flags}")
    return field_info_text_list


def get_table_field_info(cur, tablename):
    """
    Retrieves the field info associated with a table
    :param cur:
    :param tablename:
    :return:
    """
    cur.execute(f"SELECT * FROM {tablename} LIMIT 1")
    field_info = get_field_info(cur)
    return field_info


if __name__ == '__main__':
    logger = get_logger(args.verbose)
    logger.info("kontor.db_structure started")
    _, mariadb_conn = get_database_cursors(logger)
    tables = show_tables(mariadb_conn.cursor(), logger)
    for table in tables:
        field_info_text = get_table_field_info(mariadb_conn.cursor(), table)
        print(f"Columns in table {table}:")
        print("\n".join(field_info_text))
        print("\n")
    mariadb_conn.close()
    logger.info("kontor.db_structure finished")
