#!/usr/bin/python3


from globalSettings import *
import json
from global_func import *
import sqlite3
import cgi
import cgitb
cgitb.enable()

device = DeviceName

db_filename = DBPath

conn = sqlite3.connect(db_filename)
conn.text_factory = str
c = conn.cursor()



if GUI == true:
    # print "Get the form.cgiFieldStorage"
    # Create instance of FieldStorage
    form = cgi.FieldStorage()
    request_Type = form.getvalue('requestType')

else:
    print("1.create IP CFG")
    print("2.delete IP CFG")
    print("3.Read IP CFG")
    print("4.Update IP CFG")
    choice = int(input("select cgi function==>"))
    if (choice == 1):
        request_Type = 'create_IP'
    elif (choice == 2):
        request_Type = 'delete_IP'
    elif (choice == 3):
        request_Type = 'read_IP'
    elif (choice == 4):
        request_Type = 'update_IP'
    else:
        print("Enter valid choice")
    print("Reques_Type="+str(request_Type))


def form_getvalue(val):
    if val == "ip_name":
        ipName = "Ethernet"#str(input("Enter name of the ipCFG: "))
        return ipName
    if val == "ip_addr":
        ipAddr = "192.168.12.125"#str(input("Enter ip address: "))
        return ipAddr
    if val == "netmask":
        ipNetMask = "2.2.2.2"#str(input("Enter Netmask:"))
        return ipNetMask
    if val == "gateway":
        ipGateway = "255.255.0.0"#str(input("Enter gateway:"))
        return ipGateway
    if val == "dns":
        ipDns = "10.10.10.10"#str(input("Enter DNS:"))
        return ipDns
    if val == "ip_id":
        #ipID = 1
        ipID = 1 #str(input("Enter ID:"))
        return ipID
    if val == "state":
        state = 0 #int(input("Enter State:"))
        return state
    if val == "enabled":
        enabled = 1#int(input("Enter Ethernet Enabled:"))
        return enabled


def create_IP():
    cmd = "create"
    cmd_Id = get_ccm_command_id()

    if GUI == true:
        # Get data from fields
        ip_addr = form.getvalue("ip_addr")
        netmask = form.getvalue("netmask")
        gateway = form.getvalue("gateway")
        dns = form.getvalue("dns")
        enabled = form.getvalue("enabled")

    else:

        ipName = form_getvalue("ip_name")
        ip_addr = form_getvalue("ip_addr")
        netmask = form_getvalue("netmask")
        gateway = form_getvalue("gateway")
        dns = form_getvalue("dns")
        enabled = form_getvalue("enabled")

    ip_address_ipv4 = cfgValidate(ip_addr)
    netmask_ipv4 = cfgValidate(netmask)

    query = c.execute("select count(*) from ip_cfg")
    count = c.fetchone()[0]

    if (CCM == true):

        if count == 0:
            if ip_address_ipv4 == True and netmask_ipv4 == True:
                message = "set,element=ip_cfg,element_name={0},args=7,action={1},state={2},ip_address={3},subnetMask={4},defaultGateway={5},dns={6},enabled={7},uuid={8},device={9}".format(
                    ipName, cmd, 0, ip_addr, netmask, gateway, dns, enabled, cmd_Id, device)
                send_ccm_msg(message)
                response = get_ccm_response(cmd_Id)
                print(response)
                delete_ccm_response(cmd_Id)
            else:
                print(json.JSONEncoder().encode(
                    {"status": "fail", "description": "Enter valid ipv4 address, all values should be in the range 0-255"}))
        else:
            # print json.JSONEncoder().encode({"status":"fail","description":"Ethernet Already Configured"})
            update_IP()

    else:
        if count == 0:
            if ip_address_ipv4 == True and netmask_ipv4 == True:
                query = c.execute("insert into ip_cfg(ip_addr,netmask,gateway,dns,enabled,cr_date,edit_date) values(?,?,?,?,?,datetime(),datetime())",
                                  (ip_addr, netmask, gateway, dns, enabled))
                conn.commit()
                print(json.JSONEncoder().encode(
                    {"status": "success", "description": "Created Successfully"}))
            else:
                print(json.JSONEncoder().encode(
                    {"status": "fail", "description": "Enter valid ipv4 address, all values should be in the range 0-255"}))
        else:
            update_IP()

        # c.close()
        # conn.close()


def delete_IP():
    cmd = "delete"
    cmd_Id = get_ccm_command_id()

    if (GUI == true):
        ipName = form.getvalue("ip_name")
        ipID = form.getvalue("ip_id")
    else:
        ipName = form_getvalue("ip_name")
        #ipID = form_getvalue("ip_id")
    # print ipName

    query = c.execute("select id from ip_cfg where name='"+ipName+"'")
    Id = c.fetchone()[0]
    if (CCM == true):
        message = "set,element=ip_cfg,element_name={0},args=3,action={1},Id={2},uuid={3},device={4}".format(
            ipName, cmd, Id, cmd_Id, device)
        send_ccm_msg(message)
        response = get_ccm_response(cmd_Id)
        print(response)
        delete_ccm_response(cmd_Id)
    else:
        query = c.execute("delete from ip_cfg where name="+ipName+"")
        conn.commit()
        print(json.JSONEncoder().encode(
            {"status": "success", "description": "Successfully Deleted"}))
    conn.close()


def read_IP():
    cmd = "read"
    cmd_id = get_ccm_command_id()
    if(GUI == true):
        ipID = form.getvalue("ip_id")
    else:
        ipID = form_getvalue("ip_id")

    query = c.execute(
        "select id,name,state,ip_addr,netmask,gateway,dns,enabled from ip_cfg")
    dbData = []
    conn.commit()

    for col in c:
        jsonschema = {"id": col[0], "name": col[1], "state": col[2], "ip_addr": col[3],
                      "netmask": col[4], "gateway": col[5], "dns": col[6], "enabled": col[7]}
        dbData.append(jsonschema)
    conn.close()
    print(json.JSONEncoder().encode(dbData))


def update_IP():
    cmd = "update"
    cmd_Id = get_ccm_command_id()
    if (GUI == true):
        ip_addr = form.getvalue("ip_addr")
        netmask = form.getvalue("netmask")
        gateway = form.getvalue("gateway")
        dns = form.getvalue("dns")
        enabled = form.getvalue("enabled")
        ipName = "Ethernet"
        ipState = "1"

    else:

        ipName = form_getvalue("ip_name")
        ip_addr = form_getvalue("ip_addr")
        netmask = form_getvalue("netmask")
        gateway = form_getvalue("gateway")
        dns = form_getvalue("dns")
        ipState = form_getvalue("state")
        ipID = form_getvalue("ip_id")
        enabled = form_getvalue("enabled")
        # device = "LYRA-TERA-2000"

    ip_address_ipv4 = cfgValidate(ip_addr)
    netmask_ipv4 = cfgValidate(netmask)
    #query = c.execute("select id from ip_cfg where name='"+ipName+"'")
    # ipID=c.fetchone()[0]

    query = c.execute("select count(*) from ip_cfg")
    count = c.fetchone()[0]

    if (CCM == true):

        if count > 0:
            if ip_address_ipv4 == True and netmask_ipv4 == True:
                message = "set,element=ip_cfg,element_name={0},args=8,action={1},state={2},ip_address={3},subnetMask={4},defaultGateway={5},dns={6},enabled={7},uuid={8},device={9}".format(
                    ipName, cmd, ipState, ip_addr, netmask, gateway, dns, enabled, cmd_Id, device)
                send_ccm_msg(message)
                response = get_ccm_response(cmd_Id)
                print(response)
                delete_ccm_response(cmd_Id)
            else:
                print(json.JSONEncoder().encode(
                    {"status": "fail", "description": "Enter valid ipv4 address, all values should be in the range 0-255"}))
        else:
            print(json.JSONEncoder().encode(
                {"status": "fail", "description": "Name or address already used"}))

    else:
        if count > 0:
            if ip_address_ipv4 == True and netmask_ipv4 == True:
                query = c.execute("update ip_cfg set ip_addr=?,netmask=?,gateway=?,dns=?,enabled=?,edit_date=datetime()", [
                                  ip_addr, netmask, gateway, dns, enabled])
                conn.commit()
                print(json.JSONEncoder().encode(
                    {"status": "success", "description": "Updated Successfully"}))
            else:
                print(json.JSONEncoder().encode(
                    {"status": "fail", "description": "Enter valid ipv4 address, all values should be in the range 0-255"}))
        else:
            print(json.JSONEncoder().encode(
                {"status": "fail", "description": "Name or address already used"}))
    conn.close()


print("Content-type:text/html\r\n\r\n")


if request_Type == "create_IP":
    create_IP()
elif request_Type == "delete_IP":
    delete_IP()
elif request_Type == "read_IP":
    read_IP()
elif request_Type == 'update_IP':
    update_IP()
