#!/usr/bin/env python
#_*_coding:utf-8_*_

import httplib,urllib,urllib2
import json

'''
You can also use the following if you are using json.
json.dumps(data)
Remember: urlencode can encode a dict, but not a string. The output of json.dumps is a string.
'''
def Reg_from_server(host,url,username, LUID):
    port = 443
    interval = 30
    method = 'POST'
    httpClient = None
    try:
        UID = {"hostname":host,"ComUID":LUID} 
        parm = json.dumps(UID)
        httpsClient = httplib.HTTPSConnection(host,port,timeout=interval)
        httpsClient.request(method,url,parm)
     
        response = httpsClient.getresponse()
        return (response.status,response.read())
    except Exception, e:
        print e
    finally:
        if httpClient:
            httpClient.close()    

def format():
    res_status,res_data = Reg_from_server()
    logFormat = {"ComUID":res_status,
                 "ClientUID":res_data,
                 "log":[]}
    return logFormat 
def dump2reg(dicts):
    if not dicts.get('ClientUID'):
        print 'Recv ClientUID is Null.'
        return
    with open('/gms/comm/conf/js.reg','wb') as fp:
        json.dump(fp,dicts['ClientUID'],indent=1)

def detectData():
    url  = 'https://o1.t1.xiseg.com/api/o1/register'
    LUID = '1903338b-7557-4d83-9920-12eb9120d369'
    
    logFormat = {
                 "ComUID":LUID,
                 "ClientUID":Reg_from_server(),
                 "log":[]
    }
    event_type={
        u'木马': '1',
        u'僵尸网络': '1',
        u'网站': '2',
        u'攻击': '3',
    }
    if not os.path.isfile('/gms/conf/js.reg'):
        rstatus,contents = Reg_from_server(host,url,username,LUID)
        if rstatus != 200:
            print 'No connection to hosts .'
            return
        dump2reg(contents) 

    #if not os.path.isdir(comm_data.comm_js_path):
    #    os.mkdirs(comm_data.comm_js_path)

    for js_file in file_filter_bysuffix([comm_data.comm_js_path], ['.ok']):
        with open(js_file,'rb') as fp:
            datas = fp.readlines()  
        line = []
        g_dict = {}
        data = {"t":"","a":"","si":"","di":"","dp":""}
        for data in datas:
            param = data.split('|')
            LUID = param[0]
            data["t"] = param[5] 
            if event_type.has_key(parm[9]):
                flag = event_type.get(parm[9]) 
            else:
                flag = '4'
            data["a"] = flag+'-'+param[9]+'-'+ param[8]+'-'+param[10]
            data["si"] = parm[12]
            data["di"] = parm[11]
            data["dp"] = parm[15]
            logFormat['log'].append(data)
                 
def transform():
    filename = './20160811105623.596660_9FAX-VR2F-XX6W.ok'
    with open(filename,'rb') as fp:
        datas = json.load(fp)
    print datas



def main():
    #Reg2server()
    transform()

if __name__ == "__main__":
    main()
