import os,sys
import shutil
import codecs

filecontent="""// Generated by the copyconfig.  DO NOT EDIT
using System.Collections;
using System.Collections.Generic;

namespace FastBuf
{
	public partial class %s : FastBuf.ConfigExtensible
	{
%s
	    public override void Deserialize(string buffer)
		{
%s
		}

        public override int getEntry()
        {
            return entry;
        }
	}
}           """


def copyAndreanme():
    #del_folder("..\\..\\client\\Assets\\Plugins\\Libs\\Config\\Serialize\\");
    #del_folder("..\\..\\client\\Assets\\Plugins\\Libs\\Network\Serialize\\");
    for dirpath,dirnames,filenames in os.walk("..\\configs_generated\\"):
        for filename in filenames:
            if os.path.splitext(filename)[1]==".tsv":
                shutil.copy2(dirpath+filename,"..\\configs_generated\\"+filename+".bytes")
                getTalbeTitle(dirpath+filename)
                #return
    compileConfigs()
    #del_folder("..\\..\\client\\Assets\\Plugins\\Libs\\Config\\Serialize\\");
    #del_folder("..\\..\\client\\Assets\\Plugins\\Libs\\Network\Serialize\\");

def del_folder(src):
    if os.path.isfile(src):
        try:
            os.remove(src)
        except:
            pass
    elif os.path.isdir(src):
        for item in os.listdir(src):
            itemsrc = os.path.join(src,item)
            del_folder(itemsrc)
       
def copyfolder(src,dst):
    #print "-=-=-=-=-="
    for item in os.listdir(src):
        if os.path.splitext(item)[1]==".cs":
            itemsrc = os.path.join(src,item)
            itemdst = os.path.join(dst,item)
            #print item,itemsrc,itemdst
            shutil.copy(itemsrc,itemdst)
        
        #del_folder(itemsrc)
def compileConfigs():
    copyfolder("..\\libs\\","..\\configs_generated\\")
    #shutil.copy("ConfigExtensible.cs","..\\..\\client\\Assets\\Plugins\\Libs\\Config\\Serialize\\ConfigExtensible.cs")
    #shutil.copy("IExtensible.cs","..\\..\\client\\Assets\\Plugins\\Libs\\Config\\Serialize\\IExtensible.cs")
    #copyfolder("..\\..\\client\\Assets\\Plugins\\Libs\\Network\Serialize\\","..\\..\\client\\Assets\\Plugins\\Libs\\Config\\Serialize\\")
    
    #shutil.copy("..\\..\\client\\Assets\\Plugins\\Libs\\Network\Serialize\\","..\\..\\client\\Assets\\Plugins\\Libs\\Config\\Serialize\\IExtensible.cs")
    
    csc20="C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\csc.exe"
    dll="..\\configs_generated\\config_proto.dll"
    cmd="%s /out:%s /target:library /debug- /optimize+ ..\\configs_generated\\*.cs" \
         %(csc20,dll)
    print cmd
    
    os.system(cmd)
                
def getcolNameAndType(col,comment):
    #print col,comment
    col = col.strip(")");
    nametype = col.split("(")
    #print nametype
    type = nametype[1].strip(" ");
    type = type.replace("32","")
    #replace bigstring to string
    type = type.replace("big","")
    comma =type.find(":")
    if comma !=-1:
        type = type[:comma]
    name = nametype[0].strip(" ");
    return name ,type,comment
def getTalbeTitle(path):
    global filecontent
    tablename = os.path.basename(path).replace(".tsv","")
    print tablename
    fin = open(path);
    titleline = fin.readline()
    fin.close()
    titleline = titleline.strip('\n');
    #print titleline
    titlelist = titleline.split("\t");
    attribute = ""
    serialize_start ="            string[] items = buffer.Split('\t');\n"
    serialize=""
    col =0;
    for title in titlelist:
        #print title
        colname=""
        type=""
        comment=""
        bothside = title.find("|||")
        serverside = title.find("||")
        clientside = title.find("|")
        if bothside != -1:
            colname,type,comment = getcolNameAndType(title[bothside+3:],title[:bothside])
        elif serverside != -1:
            colname,type,comment = getcolNameAndType(title[serverside+2:],title[:serverside])
        elif clientside != -1:
            colname,type,comment = getcolNameAndType(title[clientside+1:],title[:clientside])
        if colname =="":
            continue;
        #if type=="string":
        #    attribute+=("	   public " + type +" " + colname + "= new string(); \t/// " + comment + " ///\n")
        #else:
        attribute+=("	   public " + type +" " + colname + "; \t/// " + comment + " ///\n")
        serialize+="            ";
        if type == "int":
            serialize+=(colname+" = ParseDecInt( items[" + str(col) +"]);\n")
        elif type == "bool":
            serialize+=(colname+" = ParseBool( items[" + str(col) +"],true);\n")
        elif type == "float":
            serialize+=(colname+" = ParseFloat( items[" + str(col) +"]);\n")
        elif type == "string":
            serialize+=(colname+" = items[" + str(col) +"];\n")
        else:
            serialize+=(colname+" = ParseEnum<"+type+">(items[" + str(col) +"]);\n")
        col+=1;
    serialize_start+=("            if(items.Length <"+str(col-2)+"){\n")
    serialize_start+=("                System.Diagnostics.Debug.WriteLine(\""+tablename+" item out of range\");\n            }\n");
    serialize = serialize_start+serialize
    fout = codecs.open("..\\configs_generated\\"+tablename+".cs","w","utf-8")
    fout.write(codecs.BOM_UTF8.decode("utf-8"))
    content = filecontent % (tablename,attribute,serialize)
    content = content.decode("utf-8")
    fout.write(content)
    fout.close();

#copyfolder("..\\..\\client\\Assets\\Plugins\\Libs\\Network\Serialize\\","..\\..\\client\\Assets\\Plugins\\Libs\\Config\\Serialize\\")
copyAndreanme()