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

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

# ファイル名: table.py
# 機能: jokenshori.pyで出力された，条件処理表を作成するためのセル情報（関数ごと）を1つに統合する．
#	条件処理表に描画する罫線の範囲情報を出力する．
# 関数: getVal, clearCheckedCellR, checkRowSizeR, checkRowAddressRightside, unionCellRow, table
# 著者名: 山本椋太，若林丈紘

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

#from parse import *

import re
import os
import shutil

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

# 関数名: getVal
# 機能: ※呼び出し元を確認できなかった
# 引数
#   exs:
#   C:
#   R:
#   c:
#   r:

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

def getVal(exs,C,R,c,r):
    if re.search("%%%MJK%%%", exs[c][r]) or exs[c][r] == "":
        return getVal(exs,C,R,c+1,r)
    else:
        return exs[c][r]

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

# 関数名: clearCheckedCellR
# 機能: ※呼び出し元を確認できなかった
# 引数
#   exs:
#   C:
#   R:
#   sta:
#   end:

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

def clearCheckedCellR(exs,C,R,sta,end):
    exs.reverse()
    staC = ord(sta[0])  - ord(C)
    staR = int(sta[1:]) - int(R)
    endC = ord(end[0])  - ord(C)
    endR = int(end[1:]) - int(R)

    for i in range(staC,endC+1):
        for j in range(staR,endR+1):
            exs[i][j] = "/"
    exs.reverse()
    return exs

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

# 関数名: checkRowSizeR
# 機能: ※呼び出し元を確認できなかった
# 引数
#   exs:
#   C:
#   R:
#   i:
#   j:

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

def checkRowSizeR(exs,C,R,i,j):
    k = 1
    while j+k < len(exs[i]):
        if exs[i][j+k] != exs[i][j]:
            break
        k += 1
    return k

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

# 関数名: checkRowAddressRightside
# 機能: ※呼び出し元を確認できなかった
# 引数
#   exs:
#   i:
#   j:

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

def checkRowAddressRightside(exs,i,j):
    self = 0
    if i > 0:
        comp = checkRowAddressRightside(exs,i-1,j)
    else:
        return 99999999

    exs[i] = exs[i][j:]
    for ex in exs[i]:
        for jj in range(j+1,len(ex)):
            self += 1
            if ex[j] != ex[jj]:
                break
    if self > comp:
        return comp
    else:
        return self



    """for ex in exs[i]:
        if i > 0:
            comp = checkRowAddressRightside(exs,i-1,j)
        else:
            return 99999999

        for jj in range(j+1,len(ex)):
            self += 1
            if ex[j] != ex[jj]:
                break
        if self > comp:
            return comp
        else:
            return self
    """


    while j+k < len(exs[i]):
        if exs[i][j+k] != exs[i][j]:
            break
        k += 1
    return k

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

# 関数名: unionCellRow
# 機能: ※呼び出し元を確認できなかった
# 引数
#   eR:
#   C:
#   R:
#   i:

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

def unionCellRow(eR,C,R,i):
    j = 0
    cnt = 0
    outstr = ""
    while j < len(eR):
        if j + 1 >= len(eR):
            break
        k = 1
        if eR[j] == "/":
            j + 1
            break
        while eR[j] == eR[j+k]:
            k += 1
            if j+k >= len(eR):
                break
        k -= 1
        if k == 0:
            outstr += chr(ord(C)+i)
            outstr += str(int(R)+j) + "\t"
            outstr += chr(ord(C)+i)
            outstr += str(int(R)+j+k) + "\t"
            outstr += eR[j] + "\n"
        else:
            outstr += chr(ord(C)+i)
            outstr += str(int(R)+j) + "\t"
            outstr += chr(ord(C)+i)
            outstr += str(int(R)+j+k) + "\t"
            outstr += eR[j] + "\n"

        j += k
        j += 1
    outstr = outstr[:-1]
    return outstr

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

# 関数名: table
# 機能: jokenshori.pyで出力された，条件処理表を作成するためのセル情報（関数ごと）を1つに統合する．
#	条件処理表に描画する罫線の範囲情報を出力する．
# 引数
#   なし

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

def table():

    #fi = open("temp/tableinfo.tsv","r")
    #funcs = fi.read()
    #fi.close()


    maxR = '1'
    maxC = 'A'
    minR = '9999'
    minC = 'Z'

    files = os.listdir("temp/tableinfo")


    for fnum,f in enumerate(files):
        fi = open("temp/tableinfo/" + f ,"r")
        lines = fi.readlines()
        fi.close()
        fo = open("temp/tableinfo/tableinfo2_" + str(fnum+1) + ".tsv","w")
        if len(lines[0]) == 0:
            del lines[0]
        elif len(lines[-1]) == 0:
            del lines[-1]
        line = lines[0]
        startcell = line.split("\t")[0]

        line = lines[-1]
        endcell = line.split("\t")[1]



        for line in lines:
            row = line.split("\t")
            if ord(row[0][0]) > ord(maxC):
                maxC = row[0][0]
            if ord(row[1][0]) > ord(maxC):
                maxC = row[1][0]
            if int(row[0][1:]) > int(maxR):
                maxR = row[0][1:]
            if int(row[1][1:]) > int(maxR):
                maxR = row[1][1:]
            if ord(row[0][0]) < ord(minC):
                minC = row[0][0]
            if ord(row[1][0]) < ord(minC):
                minC = row[1][0]
            if int(row[0][1:]) < int(minR):
                minR = row[0][1:]
            if int(row[1][1:]) < int(minR):
                minR = row[1][1:]

        excelsheet = [["" for i in range(int(maxR)-int(minR)+1)] for j in range (ord(maxC)-ord(minC)+1)]
        i = 0
        j = 0

        for line in lines:
            row = line.split("\t")
            i = ord(row[0][0]) - ord(minC)
            j = int(row[0][1:]) - int(minR)
            row[2] = row[2][:-1]

            if row[0] == row[1]:
                excelsheet[i][j] = row[2]
            else:
                if row[0][0] == row[1][0]:
                    toj = int(row[1][1:]) - int(minR)
                    while j <= toj:
                        excelsheet[i][j] = row[2]
                        j += 1
                elif row[0][1:] == row[1][1:]:
                    toi = ord(row[1][0]) - ord(minC)
                    while i <= toi:
                        excelsheet[i][j] = row[2]
                        i += 1
        tabcnt = 0


        for i,exR in enumerate(excelsheet):
            for j,ex in enumerate(exR):
                ex = ex.replace("if(%%%MJK%%%)","%%%MJK%%%")
                excelsheet[i][j] = ex
                if ex == "":
                    ex = "%%%MJK%%%"
                    excelsheet[i][j] = ex
                if i == 0:
                    continue
                elif i == ord(maxC) - ord(minC):
                    if "}" in ex:
                        tabcnt -= 1
                    excelsheet[i][j] = "  " * tabcnt + ex
                    ex = "  " * tabcnt + ex
                    if "{" in ex:
                        tabcnt += 1
                    continue
                else:
                    if i == ord(maxC) - ord(minC) - 2:
                        excelsheet[i][j] = ex.replace(" ", "")
                        ex = ex.replace(" ", "")
                        if "%%%MJK%%%" in excelsheet[i+1][j] or excelsheet[i+1][j] == "":
                            ex = "%%%MJK%%%"
                            excelsheet[i+1][j] = ex

                    else:
                        excelsheet[i][j] = ex.replace(" ", "")
                        ex = ex.replace(" ", "")


        ## create new table
        staC = minC
        staR = minR
        r_exs = excelsheet[:]


        for i,exR in enumerate(r_exs):
            outstr = ""
            if i == 0: ##関数行の処理
                outstr = staC+staR + "\t" + staC+str(len(exR)+int(staR)-1)+"\t"+exR[0] + "\n"

            elif i == 1: ##1段目のネストの処理
                c1 = chr(ord(minC) + i )
                c2 = c1
                j = 0
                while j < len(exR):
                    outstr += (c1 + str(int(staR)+j) + "\t")
                    statement = exR[j]
                    while exR[j] == statement:
                        j += 1
                        if j >= len(exR):
                            break
                    j -= 1
                    outstr += (c2 + str(int(staR)+j) + "\t")
                    outstr += statement + "\n"
                    j += 1

            elif i == len(r_exs) - 1:	#処理文の処理
                c1 = maxC
                for j in range(len(exR)):
                    outstr += (c1 + str(int(staR)+j) + "\t")*2
                    outstr += exR[j]+"\n"
                outstr = outstr[:-1]

            else: ## 2以降のネストの条件
                c1 = chr(ord(minC) + i )
                c2 = c1
                j = 0
                while j < len(exR):
                    outstr += (c1 + str(int(staR)+j) + "\t")
                    statement = exR[j]
                    k = 0
                    limit = 999999

                    while i - k > 1:
                        temp = 0
                        while r_exs[i-k][j] == r_exs[i-k][j+temp]:
                            temp += 1
                            if j + temp >= len(r_exs[i-k]):
                                break
                        if temp < limit:
                            limit = temp-1
                        k += 1
                    outstr += (c2 + str(int(staR)+limit+j) + "\t")
                    outstr += statement + "\n"
                    j += limit
                    j += 1

            print(outstr,file=fo,end="")
        print("",file=fo)
        maxR = '1'
        maxC = 'A'
        minR = '9999'
        minC = 'Z'
        del excelsheet
        del r_exs
        del exR
        fo.close()


    fo = open("temp/tableinfo/tableinfo3.tsv","w")
    fo2 = open("temp/tableinfo/tableline.tsv","w")

    files = os.listdir("temp/tableinfo")
    for f in files:
        if re.match("tableinfo2",f) == None:
            continue
        fi = open("temp/tableinfo/" + f ,"r")
        lines = fi.read()
        fi.close()
        line = lines.split("\n")
        #line.remove("")
        line = [l for l in line if l != ""]
        startcell = line[0].split("\t")[0]
        endcell = line[-1].split("\t")[1]
        print(lines,file=fo,end="")
        print(startcell + "\t" + endcell,file=fo2)
    fo.close()
    fo2.close()

if __name__ == '__main__':
    table()
