#!/usr/bin/python
# -*- coding: utf-8 -*-

import cgi, cgitb, os, sys, time, subprocess
import json

#cgitb.enable()

form = cgi.FieldStorage()
filetype = form['file'].value
TxPresent = form['TxPresent'].value

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

if file == "":
    print("No File Supplied")

else:
    file_in = '/usr/share/apache2/htdocs/preset/' + filetype
    fin = open(file_in,'r')

    with fin as json_file:
        try:
            data_json = json.load(json_file)
        except:
            print("Failed Error In File")
    json_file.close()

    def check(a,b,c):
        if a != b:
            a = b
            print(c + " Updated")
            return a
        else:
            return a
            
    def force(b,c):
        print(c + " Updated")
        return b
       
    def post():   
        fin = open(param_file_in,'r')

        with fin as json_file:
            result_json = json.load(json_file)
        json_file.close()
        
        content = data_json.get("content")
        for x in content:
            try:
                a = content.get(x)
                if isinstance(a, int):
                    result_json[x] = check(result_json[x],int(content.get(x)),x)
                else:
                    result_json[x] = check(result_json[x],content.get(x),x)
            except KeyError:
                if isinstance(a, int):
                    result_json[x] = force(int(content.get(x)),x)
                else:
                    result_json[x] = force(content.get(x),x)
            
        fout = open(param_file_out,'w')

        out = json.dumps(result_json)
        out = out.replace(',',',\n\t')
        out = out.replace('{','{\n\t')
        out = out.replace('}','\n}\n')
        out = out.replace('[','')
        out = out.replace(']','')
        out = out.replace(':',' :')

        with fout as out_file:
            out_file.write(out)
        out_file.close()

    if json.dumps(data_json.get("_comment")) == "\"Unit\"":
        param_file_in = '/usr/share/apache2/htdocs/config/UnitParamsList.json'
        param_file_out = '/usr/share/apache2/htdocs/config/UnitParamsList.json'
        post()
        os.system("sync");
        os.system("echo 1 > /var/tmp/new_unit_config");
        os.system("echo 1 > /var/tmp/new_ctrl_config");
        print("Unit Config Loaded")
        
    elif json.dumps(data_json.get("_comment")) == "\"Encoder\"":
        param_file_in = '/usr/share/apache2/htdocs/config/EncoderParamsList.json'
        param_file_out = '/usr/share/apache2/htdocs/config/EncoderParamsList.json'
        post()
        os.system("sync");
        os.system("echo 1 > /var/tmp/new_config");
        print("Encoder Config Loaded")

    elif json.dumps(data_json.get("_comment")) == "\"Decoder\"":
        param_file_in = '/usr/share/apache2/htdocs/config/DecoderParamsList.json'
        param_file_out = '/usr/share/apache2/htdocs/config/DecoderParamsList.json'
        post()
        os.system("sync");
        os.system("echo 1 > /var/tmp/new_config");
        print("Decoder Config Loaded")

    elif json.dumps(data_json.get("_comment")) == "\"Tx\"" and TxPresent != '0':
        param_file_in = '/usr/share/apache2/htdocs/config/TxParamsList.json'
        param_file_out = '/usr/share/apache2/htdocs/config/TxParamsList.json'
        post()
        os.system("sync");
        os.system("echo 1 > /var/tmp/new_tx_config");
        print("Tx Config Loaded")
      
    elif json.dumps(data_json.get("_comment")) == "\"Tx\"" and TxPresent == '0':
        print("Tx not enabled on this board")
      
    else:
        print("Meta Data Missing")
   