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

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

cgitb.enable()

form = cgi.FieldStorage()
filetype = form['type'].value
filename = form['filename'].value

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

loc = ""

if filetype == "Unit":
    loc = 'UnitParamsList.json'
elif filetype == "Encoder":
    loc = 'EncoderParamsList.json'
elif filetype == "Decoder":
    loc = 'DecoderParamsList.json'
elif filetype == "Tx":
    loc = 'TxParamsList.json'
    
param_file_in = '/usr/share/apache2/htdocs/config/' + loc 
fin = open(param_file_in,'r')

with fin as json_file:
	pre_data_json = json.load(json_file)
json_file.close()

data_json = {}
data_json["_comment"] = filetype
data_json["content"] = pre_data_json

param_file_out = '/usr/share/apache2/htdocs/preset/' + filename + '.json'

if os.path.exists(param_file_out):
    print("Failed File Already Exists")
    
  
else:
    fout = open(param_file_out,'w')

    out = json.dumps(data_json)
    out = out.replace(',',',\n\t')
    out = out.replace('{','{\n\t')
    out = out.replace('}','\n}\n')
    out = out.replace(':',' :')
    out = out.replace('\"','"')

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

    os.system("sync");
    os.system("echo 1 > /var/tmp/new_unit_config");
    os.system("echo 1 > /var/tmp/new_ctrl_config");