import requests
import json
import subprocess
import requests
import os
import sys

#注意：此处需要按照本地实际的项目路径来填写
plugpath='/home/user/code/go/plugin/plugin'

command="ls $GOPATH/pkg/mod/github.com/33cn|tail -n 1"
(status, val)=subprocess.getstatusoutput(command)
print(status)
print(val)
path = "$GOPATH/pkg/mod/github.com/33cn/"+val

def getGoDoc(xpath, ppkg, interf):
    global path
    tmpPath = ''
    tmp=interf.split('.')
    if tmp[0] == 'Chain33' and not ppkg.startswith("dapp"):
        interf = tmp[2]
        tmpPath = path 
    else:
        interf = tmp[2]
        tmpPath = plugpath 
    print(tmpPath)
    command2=("cd " + tmpPath + ";go doc " + ppkg + " " + interf)
    (status2, val2) = subprocess.getstatusoutput(command2)
    #print("status2:"+str(status2))
    #print("val2:"+val2)
    if status2 != 0:
        command2=("cd " + path + ";go doc " + "types." + interf)
        (status2, val2) = subprocess.getstatusoutput(command2)
        if status2 != 0:
            print("go doc failed: status[",str(status2) + "],val2[" +  val2 + "]")
        else:
            print("types")
    else:
        print ("pkg: " + ppkg)

    file1=open(xpath + '/' + interf + '_tmp', 'w')
    file1.write(val2)
    file1.close()

    file2=open(xpath + '/' + interf, 'w')
    flag=0
    print("---" + interf + "---")
    for line in open(xpath + '/' + interf + '_tmp'):
        name = interf.split('.')
        if line.find("type "+ name[0] + " struct {") >= 0:
            flag=1
            continue

        if flag == 1:
            if line.find("XXX_") >= 0:
                break
            else:
                if line.split()[0].find("//") >= 0:
                    continue
                elif line.find("}") >= 0:
                    break
                else:
                    result=line.split()
                    name=""
                    ty=""
                    if len(result) == 4 and result[3].find("//") < 0:
                        name=result[3].split(':')[1].split('"')[1].split(',')[0]
                    elif len(result) >= 4 and result[3].find("//") >= 0:
                        name=result[2].split(':')[1].split('"')[1].split(',')[0]
                    elif len(result) == 3:
                        name=result[2].split(':')[1].split('"')[1].split(',')[0]
                    else:
                        print(result)
                        print("parse fields failed. exit")
                        sys.exit()
                    #print(result[0]+" "+ result[1]+" "+result[2]+" "+result[3].split(':')[1].split('"')[1].split(',')[0])
                    ty=result[1]
                    print(name+" "+ty)
                    file2.write(name.strip() + ' ' + ty.strip() + '\n')
    file2.close()
    print("---------")

def getPage(cid):
    cookies = {
        'UM_distinctid': '16bd01c24457a4-0b0d5ed29524ae-19251202-1fa400-16bd01c244690a',
    }

    headers = {
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }

    params = (
        ('cid', cid),
    )

    response = requests.get('https://mapi.bityuan.com/v1/article/helps', headers=headers, params=params, cookies=cookies)
    return response
    #NB. Original query string below. It seems impossible to parse and
    #reproduce query strings 100% accurately so the one below is given
    #in case the reproduced version is not "correct".
    # response = requests.get('https://mapi.bityuan.com/v1/article/helps?cid=93', headers=headers, cookies=cookies)

def saveResponse(response, name):
    data=json.loads(response.text)
    #print(data['body'])
    file1 = open(name, 'w')
    file1.write(data['body'])
    file1.close()

def compareFields(xpath, method, msg):
    #print("compare: xpath:" + xpath)
    #print("compare: method:" + method)
    #print("compare: msg:" + msg)
    tmp=method.split('.')
    #f1 = xpath + "/types." + tmp[2]
    f1 = xpath + "/" + tmp[2]
    f2 = xpath + "/doc." + msg 
   
    command1="cat "+f1+"|sort > "+xpath + "/tmp;mv " + xpath + "/tmp " + f1
    (status1, val1)=subprocess.getstatusoutput(command1)
    print("command="+command1+",status="+str(status1))
    #print (status1)
    #print (val1)

    command2="cat "+f2+"|sort > "+xpath + "/tmp;mv " + xpath + "/tmp " + f2
    (status2, val2)=subprocess.getstatusoutput(command2)
    print("command="+command2+",status="+str(status2))
    #print (status2)
    #print (val2)

    command3="diff " + f1 + " " + f2 + "> " + xpath + "/diff"
    (status3, val3)=subprocess.getstatusoutput(command3)
    print("command="+command3+",status="+str(status3))
    #print ("status3:" + str(status3))
    #print ("val3:" + val3)

def checkInterfacesByCid(cid):
    flag = 0
    subpath='./'
    method=""
    reqMsg=""
    file2=''
    pkg=''
    seq=0

    subpath=subpath + 'tmp/' 
    print("subpath:" + subpath)
    isPathExist = os.path.exists(subpath)
    if not isPathExist:
        os.makedirs(subpath)
        print("create tmp path:" + subpath + " successfully")
    else:
        print("tmp path:" + subpath + " is already exist")

    subpath=subpath + cid
    print("subpath:" + subpath)
    isPathExist = os.path.exists(subpath)
    if not isPathExist:
        os.makedirs(subpath)
        print("create cid path:" + subpath + " successfully")
    else:
        print("cid path:" + subpath + " is already exist")
 
    rsp = getPage(cid)
    print(rsp.status_code)
    cidFile=subpath + '/' + cid
    saveResponse(rsp, cidFile)

    cidResultFile=open(subpath + '/' + 'result', 'w')
    cidResultFile.write('{\n\t"cid":' + cid + ',\n\t"result":[\n')
    for line in open(cidFile):
        #print(line)
        if flag == 0: #初始状态
            if line.find(u"请求报文[") != -1:
                flag = 1
                req=line.split('[')[1].split(']')[0]
                print(reqMsg)
                reqs=req.split('/')
                reqMsg=reqs[len(reqs)-1]
                if len(reqs) > 1:
                    for index in range(len(reqs) - 1):
                        pkg=pkg+reqs[index]+'/'    
                continue

        if flag == 1: #查找method的状态
            if line.find("method") != -1:
                #"method":"Chain33.SignRawTx",
                method=(line.split(':')[1].split(',')[0].split('"')[1])
                subpath=subpath + '/' + method
                isPathExist = os.path.exists(subpath)
                if not isPathExist:
                    os.makedirs(subpath)
                    print("create path:" + subpath + " successfully")
                else:
                    print("path:" + subpath + " is already exist")

                method=method+'.'+reqMsg
                #Chain33.SendTransaction.RawParm
                print(method)
                print(subpath)
                getGoDoc(subpath, pkg, method) 
                flag = 2
                file2=open(subpath + "/doc." + reqMsg, 'w')
                seq=seq+1
                if seq == 1:
                    cidResultFile.write('\t\t{\n\t\t\t"seq":' + str(seq) + ',\n')
                else: 
                    cidResultFile.write(',\n\t\t{\n\t\t\t"seq":' + str(seq) + ',\n')
                continue
            else:
                continue

        if flag == 2: #查找请求参数的状态
            if line.find("----|----|----") != -1:
                flag = 3
                continue
            else:
                continue

        if flag == 3: #读取请求参数中
            if line.find('|') != -1:
                param=line.split('|')
                field=param[1].strip() + ' ' + param[2].strip()
                print(field)
                file2.write(field+'\n')
                continue
            else:
                flag = 4
                file2.close()
                compareFields(subpath, method, reqMsg)
                cidResultFile.write('\t\t\t"method":"' + method + '",\n\t\t\t"msg":"' + reqMsg + '",\n')
                f=open(subpath+'/diff')
                content=f.read()
                if len(content) == 0:
                    cidResultFile.write('\t\t\t"isSame":true,\n\t\t\t"diff":""\n\t\t}')
                else:
                    cidResultFile.write('\t\t\t"isSame":false,\n\t\t\t"diff":"' + content + '"\n\t\t}')
                f.close()
                continue

        if flag == 4: #查找响应参数
            if line.find("----|----|----") != -1:
                flag=5
                continue
            else:
                continue

        if flag == 5: #读取响应参数
            if line.find('|') != -1:
                param=line.split('|')
                print(""+param[1] + ' ' + param[2])
                continue
            else:
                flag = 0
                subpath='./tmp/' + cid
                method=""
                reqMsg=""
                file2=''
                pkg=''
                continue 
    cidResultFile.write(']\n\t}')
    cidResultFile.close()

def collectResults(cids):
    file=open('./result', 'w')
    file.write('{\n\t"result":[\n')
    cnt=0
    for cid in cids:
        cnt=cnt+1
        tmpFile = open('./tmp/' + cid + '/result', 'r')
        content = tmpFile.read()
        if cnt == 1:
            file.write('\t' + content)
        else:
            file.write(',\n\t' + content)
        tmpFile.close()

    file.write(']\n}\n')

    file.close()


cids = ['93', '94', '100','99','98','97','96','102','105','104','108','110','115','118','134','135']
#cids = ['93']
for cid in cids:
    checkInterfacesByCid(cid)

collectResults(cids)

