#! /usr/bin/env python3

import sys
import pymysql

sys.path.insert(0, '../Mittwoch')
from utilities import hide_exception


def db_connect(credentials: dict):
    connection = pymysql.connect(**credentials)

    return connection


def list_hosts(connection):
    cursor = connection.cursor()
    # Simple: SELECT * FROM hosts
    sql = """
          SELECT name, length(name) AS namelen, domain, address
          FROM hosts
          ORDER BY name
          """
    cursor.execute(sql)

    #print(cursor.description)
    # cursor ist Iterator
    # Hausarbeit: Konvertierung von tupel zu dict als Funktion :-)
    # for row in named(cursor):
    for row in cursor:
        #print(list(zip(cursor.description, row)))
        #print(list(zip(map(lambda d:d[0], cursor.description), row)))
        # Dictionary Comprehension
        # mydict = { i: i**10 for i in range(10) }
        # row = {k:v for k, v in zip(map(lambda d:d[0], cursor.description), row)}
        #print(list(zip(map(lambda d:d[0], cursor.description), row)))
        #print(tuple(zip(map(lambda d:d[0], cursor.description), row)))
        row = dict(zip(map(lambda d:d[0], cursor.description), row))
        print("{name:20} {address:15} {domain}".format(**row))

    # for name, domain, address in cursor:
    #     pass


def main():
    # Bitte aus Konfigurationsdatei lesen
    credentials = dict(host='notebook14',
                       user='python',
                       password='villa',
                       database='inventory')
    db = db_connect(credentials)

    list_hosts(db)

    # Verbindung sauber trennen
    db.close()


hide_exception(main)
