#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Formatting docstring for ConvManyoDoxy2Swig results

   Output files of ConvManyoDoxy2Swig are the swig interface file (XXX.i).
   This script renames XXX.i to XXX.p and formatting XXX.p file to output as XXX.i.

"""

from __future__ import print_function
import os
import glob

def Formatting( in_file, out_file ):
    """Formatting docstrng of in_file to output to out_file
    
    Args:
        in_file (string): Input file ( XXX.p, copied output file from ConvManyoDoxy2Swig  )
        out_file (string): Output file ( XXX.i )

    """
    out_list = []
    funcs_dic = {}

    f = open(in_file,"r")
    while(True):
        a_line = f.readline()
        if a_line=="":
            break
        if a_line.find('%feature("docstring")')!=0:
            out_list.append( a_line+"\n" )
            continue
        else:
            ind = a_line.find(' "')
            key_c = a_line[:ind]
            v=key_c.split(" ")
            v2 = []
            for v1 in v:
                if v1!="":
                    v2.append(v1)
            Key = v2[1]
            bar = ""
            Method = a_line[(ind+2):]

            LoopOn = True
            ind2 = Method.find('";')
            if ind2<0:
                Bar = ""
                if len(Method.strip())!=0:
                    for i in range(len(Method)):
                        Bar += "="
                    #Conts = Bar+"\n"+Method+Bar+"\n"
                    Conts = Method+Bar+"\n"
                else:
                    Conts = Method + "\n"
            else:
                Conts = Method[:ind2]+"\n"
                LoopOn = False
            Indent_spc = "    "
            Indent_spc_add = ""
            while(LoopOn):
                a_line2 = f.readline()
                if a_line2=="":
                    break
                a_line2 = a_line2.strip()
                if a_line2=="":
                    continue
                if a_line2.find("----------")>=0:
                    continue
                
                if a_line2.find("Args:")>=0 or a_line2.find("Returns:")>=0:
                    ind2 = a_line2.find('";')
                    if ind2<0:
                        Conts += ("\n"+Indent_spc+a_line2+"\n")
                    else:
                        Conts += ("\n"+Indent_spc+a_line2[:ind2]+"\n")
                        break
                    Indent_spc_add = "    "
                    continue

                ind2 = a_line2.find('";')
                if ind2<0:
                    Conts += (Indent_spc+Indent_spc_add+a_line2+"\n")
                else:
                    Conts += (Indent_spc+Indent_spc_add+a_line2[:ind2]+"\n")
                    break

            if Key in funcs_dic.keys():
                funcs_dic[Key] += Indent_spc+"\n"
                funcs_dic[Key] += Conts
            else:
                funcs_dic[Key] = (Conts+"\n")
                out_list.append("UTSUSEMI_DICKEY:"+Key+"\n")

    f.close()

    fo = open(out_file,"w")
    for item in out_list:
        k = item.strip()
        if k=="":
            continue
        ind = k.find("UTSUSEMI_DICKEY")
        if ind==0:
            key = k.replace("UTSUSEMI_DICKEY:","")
            tmp = '%feature("docstring") '+key+' "'+funcs_dic[key]+'";\n'
            fo.write(tmp)
        else:
            fo.write(item)
    fo.close()

#####################################
if __name__ == '__main__':
    hh_list = glob.glob("interfaces/*.i")
    for a_file in hh_list:
        i_path=a_file
        p_path=a_file.replace(".i",".p")
        if os.path.exists( i_path ):
            os.system( "mv %s %s"%(i_path, p_path) )
            Formatting( p_path, i_path )
    
