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

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

# ファイル名: add_else.py
# 機能: 条件式に状態変数を含む制御構文にelse句がない場合，無処理のelseを挿入する．
# 関数: add_else
# 著者名: 山本椋太，若林丈紘

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

import re
import os
import shutil
import sys

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

# 関数名: add_else
# 機能: 条件式に状態変数を含む制御構文にelse句がない場合，無処理のelseを挿入する．
# 引数
#   param: 状態変数
#   func: 解析対象の関数名
#   directory: 解析対象の関数に関する情報がまとめられたディレクトリ

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

def add_else(param, func, directory):

    print("\n===============")
    print("= add_else =")
    print("param: ", param)
    print("func: ", func)
    print("directory: ",directory)
    print("===============\n")

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

    # 関数: add_else
    # 機能：条件式に状態変数を含む制御構文にelse句がない場合，無処理のelseを挿入する


    # INPUT ： idlist2-3.tsv, sequence6-3.tsv, stlist2.tsv
    # OUTPUT: idlist2-4.tsv, sequence6-4.tsv, stlist3.tsv

    # INPUTの入力元 : temp/FUNCTION/ (FUNCTIONは任意の関数名)
    # OUTPUTの出力先: temp/FUNCTION/ (FUNCTIONは任意の関数名)

    # idlist2-3.tsv   : 各関数における条件式の一覧
    # stlist2.tsv     : 各関数における処理の一覧
    # sequence6-3.tsv : 条件式（ID)と，その制御構造に内包されるID，STの一覧

    # idlist2-4.tsv   : idlist2-3.tsvに機能を適用させたファイル
    # stlist3.tsv   : stlist2.tsvにに機能を適用させたファイル
    # sequence6-4.tsv : sequence6-3.tsvに機能を適用させたファイル

    # この関数はver1.351 add_mujoken_statement.py中の機能をモジュール化したものである．
    # 170925以前との差分を確認する場合は，add_mujoken_statement.pyを参照すること．

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

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

    rfile = out_directory + "idlist2_3.tsv"
    fi = open(rfile)
    id_lines = fi.readlines()
    fi.close()

    rfile = out_directory + "sequence6_3.tsv"
    fi = open(rfile)
    sq_lines = fi.readlines()
    fi.close()

    rfile = out_directory + "stlist2.tsv"
    fi = open(rfile)
    st_lines = fi.readlines()
    fi.close()

    fo_id = open(out_directory+"idlist2_4.tsv",'w')
    fo_sq = open(out_directory+"sequence6_4.tsv",'w')
    fo_st = open(out_directory+"stlist3.tsv",'w')

    # added_170925
    # ネストの最大深さを取得する
    maxnest = 0
    for id_line in id_lines:
        nest = int(id_line.split("\t")[2])
        if nest > maxnest:
            maxnest = nest

    # 状態変数を含む制御構文にelse句がない場合，無処理のelseを挿入する
    jotaiflg = False
    jotai_nest = 0
    else_line = ""
    id_lines_size = len(id_lines)
    ELSE_insert_flg = False
    jotai_startid = ""
    jotai_lastid = ""

    for i,id_line in enumerate(id_lines):
        temp = id_line.split("\t")
        id = temp[0]
        code = temp[1]
        nest = int(temp[2])

        if (jotaiflg == True and  nest < jotai_nest)  or\
            (jotaiflg == True and nest == jotai_nest and "%%%MJK%%%" in code):
            ELSE_insert_flg = True
            break

        if (jotaiflg == True and i == len(id_lines)-1) and not(re.match("else\s*$",code)):
            ELSE_insert_flg = True
            break

        if param in code and (code[:2] == "if" or code[:7] == "else if"):
            jotai_lastid = id
            if jotaiflg == False:
                jotai_startid = id
                jotai_nest = nest
                jotaiflg = True

        # 状態遷移に関するifブロックの末尾にelse文があれば，
        # elseの挿入は必要ないのでこの処理を飛ばす
        if jotaiflg == True and re.match("else\s*$",code) and nest == jotai_nest:
            break

    # added_170925 この行以降すべて
    # ELSE文の挿入が発生しない場合は，以降の処理はいらないので，
    # idlines2-4.tsv, stlist3.tsv, sequence6-4.tsvに書き出して終了する
    if ELSE_insert_flg==False:
        for id_line in id_lines:
            print (id_line,file=fo_id,end="")
        fo_id.close()
        for st_line in st_lines:
            print (st_line,file=fo_st,end="")
        fo_st.close()
        for sq_line in sq_lines:
            print (sq_line,file=fo_sq,end="")
        fo_sq.close()
        return
    else:
        print(jotai_nest,maxnest)
        elseid = "ID" + str(id_lines_size + 1)
        elsecode = "else"
        elsenest = str(jotai_nest)
        else_line = elseid + "\t" + elsecode + "\t" + elsenest + "\n"
        id_lines.insert(i,else_line)
        st_lines.append("$$$NONE$$$\n")

        # 状態遷移のif文が最深ネストでないなら，列幅を揃えるために，else文の内側に無条件を追加する
        if maxnest-jotai_nest == 0:
            sq_lines.insert(i,elseid+"\t"+ "ST"+str(len(st_lines))+"\t\n")
        else:
            sq_lines.insert(i,elseid+"\t"+ "ID"+str(id_lines_size + 2) +"\t\n")

            for j in range(maxnest-jotai_nest):
                MJKid = "ID" + str(id_lines_size + 2 + j)
                MJKcode = "if(%%%MJK%%%)"
                MJKnest = str(jotai_nest+1+j)
                MJK_line = MJKid + "\t" + MJKcode + "\t" + MJKnest + "\n"

                id_lines.insert(i+j+1, MJK_line)
                if j == maxnest-jotai_nest-1:
                    sq_lines.insert(i+j+1,MJKid+"\t"+ "ST"+str(len(st_lines))+"\t\n")
                else:
                    sq_lines.insert(i+j+1,MJKid+"\t"+ "ID"+str(id_lines_size + 3 + j) +"\t\n")

        for k,sq_line in enumerate(sq_lines):
            print(sq_line)
            other_ids = sq_line.split("\t")[1:]
            print(other_ids)
            if jotai_startid in other_ids:
                sq_lines[k] = sq_line.replace(jotai_lastid, jotai_lastid+"\t"+elseid)
                break

    # elseを挿入したid_lines, sq_linesのID番号を振り直す
    idcnt = 1
    jotaicnt = 0
    newid_lines = []
    newsq_lines = []
    id_reassigns = []

    for i,sq_line in enumerate(sq_lines):
        sq_temp = sq_line.split("\t",1)
        sq_id = sq_temp[0]
        rest_sq_line = sq_temp[1]

        il_temp = id_lines[i].split("\t",1)
        il_id = il_temp[0]
        rest_id_line = il_temp[1]

        reassign_id = "ID" + str(idcnt)
        id_reassigns.append((sq_id,reassign_id + "new"))

        newsq_line = reassign_id + "new" + "\t" + rest_sq_line
        newsq_lines.append(newsq_line)

        newid_line = reassign_id + "\t" + rest_id_line
        newid_lines.append(newid_line)
        idcnt += 1

    id_lines = newid_lines
    sq_lines = newsq_lines

    reassign_cnt = 0
    for i,sq_line in enumerate(sq_lines):
        ids = sq_line.split("\t")
        for j,target_id in enumerate(ids):
            for re_id in id_reassigns:
                if target_id == re_id[0]:
                    ids[j] = re_id[1]
                ids[j] = ids[j].replace("new","")
        sq_lines[i] = "\t".join(ids)

    # sq_linesのST番号を振り直し，番号に合わせてstを並べ直す
    stcnt = 1
    newst_lines = []

    for i, seq in enumerate(sq_lines):
        row = seq.replace("\n","").split("\t")
        line = ""
        for r in row:
            if "ID" in r:
                line += r+"\t"
                continue
            if "ST" in r:
                stnum = int(r[2:])
                newst_lines.append(st_lines[stnum-1])
                line += "ST" + str(stcnt) + "\t"
                stcnt += 1
        sq_lines[i] = line + "\n"

    st_lines = newst_lines
    stnum_move_flg = False

    for id_line in id_lines:
        print (id_line,file=fo_id,end="")
    fo_id.close()

    for i,st_line in enumerate(st_lines):
        print (st_line,file=fo_st,end="")
    fo_st.close()

    for sq_line in sq_lines:
        print (sq_line,file=fo_sq,end="")
    fo_sq.close()
