import socket
import sys
import logging
import urllib
import MySQLdb 
from thread import *
 
HOST = '103.247.11.59' # Symbolic name meaning all available interfaces 
PORT = 8080 # Arbitrary non-privileged port 
#logging.basicConfig(filename='terminalsrv.log',level=logging.DEBUG)
#db = MySQLdb.connect(host='localhost', usermspsilaw_dc',passwd='candi105137',db="mspsilaw_dataicu")
#cursor = db.cursor()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
print 'Socket created'
 
#Bind socket to local host and port
try:
    s.bind((HOST, PORT)) 
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
     
print 'Socket bind complete'
 
#Start listening on socket
s.listen(10) 
print 'Socket now listening'
 
#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    #conn.send('Welcome to the server. Type something and hit enter\n') 
#send only takes string
    while True:
        #infinite loop so that function do not terminate and thread do not end.
        #Receiving from client
        data = conn.recv(1024)
        if len(data)>0:
            db = MySQLdb.connect(host='localhost', usermspsilaw_dc',passwd='candi105137',db="mspsilaw_dataicu")
            cursor = db.cursor()
            content = data.split("report=")
            detailcontent = content[1].split("%0A")
            d_data =['','','','','','','','','','','','','','','','']
            for val in range(len(detailcontent)):
                if val==16:
                    break
                row = detailcontent[val].split(":")
                if val==1:
                    buff=row[1]+":"+row[2]+":"+row[3]
                    d_data[val]=urllib.unquote(buff).decode()
                else:
                    d_data[val] = urllib.unquote(row[1]).decode()
            sql = """insert into datalog (f, dt, id_dev, x1, x2, x3,x4, x5, x6, x7, x8, a1, a2, a3, y1, y2) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
            cursor.execute(sql, d_data)
            db.commit()
            cursor.close()
            db.close()
            #logging.debug(content[1])
            break
     
    #came out of loop
    conn.close()
 
#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
     
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))
    print 'Disconnected with ' + addr[0] + ':' + str(addr[1]) 
s.shutdown(socket.SHUT_WR) 
s.shutdown(socket.SHUT_RD) 
s.close()