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

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

cgitb.enable()
#cgi.test()

param_file_in = '/home/root/ctrl/encoder/EncoderParamsList.json' 
fin = open(param_file_in,'r')

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

result = {'success':'true','message':'The Command Completed Successfully'};

content_len = int(os.environ["CONTENT_LENGTH"])

req_body = sys.stdin.read(content_len)
myjson = json.loads(req_body)

print 'Content-Type: application/json\n\n'
#print json.dumps(result)
EncodeMode   = int(myjson.get('EncodeMode'))
VideoFormat  = int(myjson.get('VideoFormat'))
ChromaFormat = int(myjson.get('ChromaFormat'))
BitDepth 	 = int(myjson.get('BitDepth'))
SampleFormat = int(myjson.get('SampleFormat'))
LowDelayMode = int(myjson.get('LowDelayMode'))

if(EncodeMode != 0 and LowDelayMode == 2):
	LowDelayMode = 1
	
if(EncodeMode != 0 and VideoFormat > 22):
	VideoFormat = 22

if(EncodeMode == 1 and BitDepth == 1):
	BitDepth = 0

#if(SynergyMode  != 0 and SampleFormat != 1):
#	SampleFormat = 1

enc_data_json["EncodeMode"]		= EncodeMode;
enc_data_json["VideoFormat"]	= VideoFormat;
enc_data_json["ChromaFormat"]	= ChromaFormat;
enc_data_json["BitDepth"]		= BitDepth;
enc_data_json["SampleFormat"]	= SampleFormat;
enc_data_json["LowDelayMode"]	= LowDelayMode;

#enc_data_json = myjson;

#print LowDelayMode
#print VideoFormat
#print ChromaFormat
#print BitDepth
#print SampleFormat

param_file_out = '/home/root/ctrl/encoder/EncoderParamsList.json' 
fout = open(param_file_out,'w')

out = json.dumps(enc_data_json)
out = out.replace(',',',\n\t')
out = out.replace('{','{\n\t')
out = out.replace('}','\n}\n')
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_config");
