#!/usr/bin/python3
# coding=utf-8

from bottle import route, run, static_file, template
import MySQLdb

HOST = 'localhost'


@route('/static/')
def server_static(filepath):
    return static_file(filepath, root='/home/mix/PycharmProjects/kea_for_miners/static/')


@route('/')
def server_homepage():
    dbhost = '10.5.1.248'
    dbuser = 'kea'
    dbpass = 'kea1234'
    dbbase = 'dhcp4'
    sql = "SELECT " \
          " expire, " \
          " INET_NTOA(address) as ip4, " \
          " HEX(hwaddr)as hw_addr, " \
          " hostname " \
          " FROM lease4 " \
          "where INET_NTOA(address) like '10.5.0%'" \
          " ORDER BY expire DESC;"
    try:
        conn = MySQLdb.connect(host=dbhost, user=dbuser,
                               passwd=dbpass, db=dbbase)
    except MySQLdb.Error as err:
        print("Connection error: {}".format(err))
        conn.close()
    try:
        cur = conn.cursor(MySQLdb.cursors.DictCursor)
        cur.execute(sql)
        data = cur.fetchall()
    except MySQLdb.Error as err:
        print("Query error: {}".format(err))
    conn.close()
    data_list = []
    for row in data:
        temp = []
        temp.append(row['expire'])
        temp.append(row['ip4'])
        temp.append(row['hw_addr'])
        temp.append(row['hostname'])
        data_list.append(temp)
    return template('main.tpl', A=data_list)


@route('/hosts/')
def server_hosts_repo():
    dbhost = '10.5.1.248'
    dbuser = 'kea'
    dbpass = 'kea1234'
    dbbase = 'dhcp4'
    sql = "SELECT " \
          "INET_NTOA(hosts.ipv4_address) AS ip4," \
          " hosts.hostname," \
          " HEX(dhcp_identifier)as hw_addr, " \
          "	if(hex(inet_ntoa(lease4.address)), '+','-') as leased " \
          "FROM " \
          " hosts " \
          "LEFT JOIN" \
          " lease4" \
          " on" \
          "	 dhcp_identifier = hwaddr " \
          "ORDER BY ip4;" \
#          "where " \
#          " INET_NTOA(hosts.ipv4_address) LIKE '10.5.1%';"
    try:
        conn = MySQLdb.connect(host=dbhost, user=dbuser,
                               passwd=dbpass, db=dbbase)
    except MySQLdb.Error as err:
        print("Connection error: {}".format(err))
        conn.close()
    try:
        cur = conn.cursor(MySQLdb.cursors.DictCursor)
        cur.execute(sql)
        data = cur.fetchall()
    except MySQLdb.Error as err:
        print("Query error: {}".format(err))
    conn.close()
    data_list = []
    for row in data:
        temp = []
        temp.append(row['ip4'])
        temp.append(row['hostname'])
        temp.append(row['hw_addr'])
        temp.append(row['leased'])
        data_list.append(temp)
    print(data_list)
    return template('hosts.tpl', A=data_list)


run(host='0.0.0.0', port=8080, debug=True)
