#!/usr/bin/env python
# coding: Shift_JIS

# ##############################

# ファイル名: deletefunction.py
# 機能: Excel上でユーザが選択した状態変数がローカル変数の場合，Cファイルにおいてその変数が定義される関数以外の記述部分を削除する．
# 関数: deleteFunctionFromID, getCondVal, deletefunction
# 著者名: 山本椋太，若林丈紘

# ##############################

import re
import os
import shutil
import sys

# ##############################

# 関数名: deleteFunctionFromID
# 機能: ID中の記述について，削除するか判断する．
# 引数
#   target: IDの識別番号
#   param: 状態変数
#   ids: IDについてまとめられたファイル
#   st: ※関数中で使用されていない

# ##############################

#(added 2017_0202)
#nest > 0 then return 2
#nest = 0 then return 0 or 1
def deleteFunctionFromID(target,param,ids,st):
    id1 = ids[int(target[2:])-1]
    id1 = id1.replace("\n","")
    row = id1.split("\t")
    if row[2] != '0':
        return 2
    print("-------------")
    checkids = ids[int(target[2:]):]

    for ci in checkids:
        print("DEL_ID",target,ci)
        ci = ci.replace("\n","")
        row = ci.split("\t")
        if row[2] == '0':
            return 0
        #(added 2017_0324_wakabayashi)
        #if param in row[1]:
        if param in row[1] and int(row[2])>1:
            return 1
    return 0

# ##############################

# 関数名: getCondVal
# 機能: ※呼び出し元を確認できなかった
# 引数
#   instring:
#   param:

# ##############################

def getCondVal(instring,param):
    row = instring.split("==")
    if row[0] == param:
        return row[1]
    else:
        return ""

# ##############################

# 関数名: deletefunction
# 機能: Excel上でユーザが選択した状態変数がローカル変数の場合，Cファイルにおいてその変数が定義される関数以外の記述部分を削除する．
# 引数
#   param: 状態変数
#   funcname: 状態変数が定義されている関数
#   directory: 解析対象の関数に関する情報がまとめられたディレクトリ

# ##############################

def deletefunction(param, funcname,directory):

    print("\n===============")
    print("deletefunction")
    print("===============\n")

    out_directory = "temp/" + directory + "/"

    #rfile = out_directory + "idlist2.tsv"
    rfile = out_directory + "idlist2_5.tsv"
    fi = open(rfile)
    lines = fi.readlines()
    fi.close()

    elsecnt = 0
    elselist = []
    elseconds = []
    elsevals = []
    elseids = []

    vals = []
    temp_valid = []


    ## 関係のない関数の削除

    #fi = open(out_directory+"idlist2.tsv","r")
    fi = open(out_directory+"idlist2_5.tsv","r")
    lines = fi.readlines()
    fi.close()


    funcs = []
    deletefuncnames = []
    fo = open("lists/deletefunctions.txt","a")

    for i,line in enumerate(lines):
        line = line[:-1]
        row = line.split("\t")
        if row[2] == "0" and row[1] != funcname and funcname != "GLOBAL":
            deletefuncname = row[1]
            deletefuncname = deletefuncname.split(" ")[1]
            deletefuncname = deletefuncname.split("(")[0]
            deletefuncnames.append(deletefuncname)
            print("\n" + deletefuncname,file=fo,end="")

        if i == 0:
            continue
        if row[2] == "0":
            funcs.append(int(lines[i-1].split("\t")[0][2:])-1)
    funcs.append(len(lines) - 1)
    fo.close()

    stats = []

    #fi = open(out_directory + "sequence6.tsv","r")
    fi = open(out_directory + "sequence6_5.tsv","r")
    lines = fi.readlines()
    fi.close()

    for i,f in enumerate(funcs):
        if i == 0:
            lines2 = lines[0:f+1]
        else:
            lines2 = lines[funcs[i-1]:f+1]

        lines2.reverse()

        flg = False
        for line2 in lines2:
            row2 = line2.split("\t")
            row2.reverse()
            for r2 in row2:
                if "ST" in r2:
                    r2 = r2.replace("\n","")
                    stats.append(int(r2[2:]) - 1)
                    flg = True
                    break
            if flg == True:
                break


    #fi = open(out_directory + "idlist2.tsv","r")
    fi = open(out_directory + "idlist2_5.tsv","r")
    allid = fi.readlines()
    fi.close()

    fi = open(out_directory + "stlist4.tsv","r")
    allst = fi.readlines()
    fi.close()

    delete_target = []
    ok_target = []

    print("funcs")
    print(funcs)

    for id1 in allid:
        id1 = id1.replace("\n","")
        row = id1.split("\t")
        judge = deleteFunctionFromID(row[0],param,allid,allst)
        if judge == 0:
            delete_target.append(row[0])
        elif judge == 1:
            ok_target.append(row[0])
        elif judge == 2:
            id1 = id1
        else:
            if funcname == "GLOBAL":
                print("WORNING:001"+"\n"+row[0])
    #            input()
                continue
            else:
                print("ERROR:001")
                exit()

    if funcname == "GLOBAL":
        print("UNDEFINED")
    #    exit()

    else:
        for id1 in allid:
            id1 = id1.replace("\n","")
            row = id1.split("\t")
            if row[2] != '0':
                continue
            if re.search("[ \t]+"+funcname+"[ \t]*\(",row[1]) == None:
                if row[0] not in delete_target:
                    delete_target.append(row[0])
                if row[0] in ok_target:
                    del ok_target[ok_target.index(row[0])]




    print("del_target::",delete_target)
    print("ok_target::",ok_target)
    print("param",param)

    #ok_targetのソート
    temp = list()
    for ot in ok_target:
        index = int(ot[2:])
        temp.append(index)
    temp.sort()

    ok_target = list()
    for t in temp:
        ok_target.append("ID"+str(t))

    #delete_targetのソート
    temp = list()
    for dt in delete_target:
        index = int(dt[2:])
        temp.append(index)
    temp.sort()

    delete_target = list()
    for t in temp:
        delete_target.append("ID"+str(t))


    if len(ok_target) == 0: return False


    #関数を削除したidlistとsequenceの作成
    #fi = open(out_directory + "idlist2.tsv",'r')
    fi = open(out_directory + "idlist2_5.tsv",'r')
    lines = fi.readlines()
    fi.close()

    #fi = open(out_directory + "sequence6.tsv",'r')
    fi = open(out_directory + "sequence6_5.tsv",'r')
    seq = fi.readlines()
    fi.close()

    fo_sq = open(out_directory+"sequence7.tsv",'w')
    fo_id = open(out_directory+"idlist3.tsv",'w')

    ok_idnumber = list()
    for ot in ok_target:
        ok_idnumber.append(int(ot[2:]))
    print("temp",temp)

    for oi in ok_idnumber:
        cnt = oi
        print("cnt,oi,line[oi-1],seq[oi-1]",cnt,oi,lines[oi-1],seq[oi-1])
        print(lines[oi-1],end="",file=fo_id)
        print(seq[oi-1],end="",file=fo_sq)

        while cnt < len(lines):
            line = lines[cnt].replace("\n","")
            row = line.split("\t")
            if row[2] == '0':
                break
            print(line,file=fo_id)
            print(seq[cnt],end="",file=fo_sq)
            cnt += 1

    fo_id.close()
    fo_sq.close()


    #idlistとsequenceのID番号の振り直し
    fi = open(out_directory + "sequence7.tsv",'r')
    seq = fi.readlines()
    fi.close()

    fi = open(out_directory + "idlist3.tsv",'r')
    lines = fi.readlines()
    fi.close()

    idcnt = 1
    stcnt = 1

    for i,l in enumerate(lines):
        l = l.replace("\n","")
        row = l.split("\t")
        target = row[0]
        regep = target+"(\\t|\\n|$)"

        for j,s2 in enumerate(seq):
            temp = re.sub(regep,"ID"+str(idcnt),s2)
            temp = temp.split("ID")
            if len(temp) == 2:
                temp2 = temp[1].split("ST")
                temp[1] = temp2[0]
                for t2 in temp2[1:]:
                    if "ST"+t2 not in temp:
                        temp.append("ST"+t2)
            result = ""
            for t in temp:
                t = t.replace("\t","")
                if t == '':
                    continue
                if "ST" in t:
                    result += t + "\t"
                else:
                    result += "ID"+t +"\t"
            result = result[:-1].replace("\n","")
            seq[j] = result+"\n"
            lines[j] = re.sub(regep,"ID"+str(idcnt)+"\t",lines[j])
        idcnt += 1

    fo_sq = open(out_directory+"sequence8.tsv",'w')
    fo_id = open(out_directory+"stm_idlist.tsv",'w')

    for s in seq:
        print(s,end="",file=fo_sq)

    for l in lines:
        print(l,end="",file=fo_id)
    fo_id.close()
    fo_sq.close()


    #stlistとsequenceのST番号の振り直し
    fi = open(out_directory + "sequence8.tsv",'r')
    seq = fi.readlines()
    fi.close()

    fi = open(out_directory+"stlist4.tsv",'r')
    sts = fi.readlines()
    fi.close()

    fo_sq = open(out_directory+"stm_sequence.tsv",'w')
    fo_st = open(out_directory+"stm_stlist.tsv",'w')
    stcnt = 1
    for i, sq in enumerate(seq):
        sq = sq.replace("\n","")
        row = sq.split("\t")
        line = ""
        for r in row:
            if "ID" in r:
                line += r+"\t"
                continue
            temp = int(r[2:])
            print(sts[temp-1],end="",file=fo_st)
            line += "ST" + str(stcnt) + "\t"
            stcnt += 1
        print(line[:-1],file=fo_sq)

    fo_st.close()
    fo_sq.close()

if __name__ == '__main__':
    deletefunction(sys.argv[1],sys.argv[2],sys.argv[3])
