#!/bin/python3
#-*- coding:utf-8 -*-
# grbh0226@gmail.com2019-08-09 10:14:17

import os
import sys
from datetime import *
import time
from string import Template
import getopt
import collections
from optparse import OptionParser


projectPath = os.getenv('GenCodeProjectPath',"")
if projectPath == '':
    projectPath = os.environ["HOME"]+"/xxproject/src"
serverName = ""




def write_file(filepath,str_code):
    #检测目录，不存在 mkdir
    print(filepath)
    name = os.path.basename(filepath)
    if False == os.path.exists(os.path.dirname(filepath)):
        os.makedirs(os.path.dirname(filepath))
        print("mkdir "+os.path.dirname(filepath)+" ...")

    with open(filepath,"w") as f:
        f.write(str_code)
        # for line in lines:
            # f.write(line)
    print("gen "+filepath+" ...")

def read_tpl(tpl_filename):
    # TODO 更健壮的文件读,文件缺少时，更友好的指导
    with open(tpl_filename,'r') as f:
        str_tpl = f.read()
    return str_tpl


def gen_template(tpl_filename):
    # TODO 更健壮的 检查
    return Template(read_tpl(tpl_filename))

def Cap(name):
    # 首字母大写,添加 C 在单词首
    # TODO
    # 需要更加健壮
    return "C"+name[0:1].capitalize()+name[1:]

def get_head_comment(year,formateTime,fileName):
    # TODO must be str
    comment_tpl = gen_template('template/head_comment.tpl')
    # print(comment_tpl.substitute(Year='Year',Filename=''FileName,FormateTime=FormateTime))
    return comment_tpl.substitute(Year=year,Filename=fileName,FormateTime=formateTime)

def single_case_class(name):
    ClassName = Cap(name)
    h_filename = name + ".h"

    h_tpl = gen_template('template/cpp_single_class_h.tpl')
    cpp_tpl = gen_template('template/cpp_single_class_cpp.tpl')

    curr_date = datetime.fromtimestamp(time.time())
    FormateTime = curr_date.strftime('%Y-%m-%d %H:%M:%S')
    head_comment = get_head_comment(str(curr_date.year),str(FormateTime),name+'.h')
    head_comment2 = get_head_comment(str(curr_date.year),str(FormateTime),name+'.cpp')

    h_file_str = head_comment + h_tpl.substitute(ClassName=ClassName)
    cpp_file_str= head_comment +cpp_tpl.substitute(HeadName=name,ClassName=ClassName)
    return h_file_str,cpp_file_str


def common_class(name):
    ClassName = Cap(name)
    h_filename = name + ".h"

    curr_date = datetime.fromtimestamp(time.time())
    FormateTime = curr_date.strftime('%Y-%m-%d %H:%M:%S')
    head_comment = get_head_comment(str(curr_date.year),str(FormateTime),name+'.h')
    head_comment2 = get_head_comment(str(curr_date.year),str(FormateTime),name+'.cpp')

    h_tpl = gen_template('template/cpp_class_h.tpl')
    cpp_tpl = gen_template('template/cpp_class_cpp.tpl')

    h_file_str = head_comment + h_tpl.substitute(ClassName=ClassName)
    cpp_file_str = head_comment + cpp_tpl.substitute(HeadName=name,ClassName=ClassName)
    return h_file_str,cpp_file_str

def gen_class(name,singleCase):
    print("gen_class "+str(singleCase))

    global serverName
    h_filename = name + ".h"
    cpp_filename = name + ".cpp"
    h_filepath = os.path.join(projectPath,serverName,h_filename)
    cpp_filepath = os.path.join(projectPath,serverName,cpp_filename)
    if True == os.path.exists(h_filepath):
        # TODO
        print(h_filepath +" exists!!!")
        return

    if 1==singleCase:
        h_str,cpp_str = single_case_class(name)
    else:
        h_str,cpp_str = common_class(name)

    if 0==len(h_str) or 0==len(cpp_str):
        return
    write_file(h_filepath,h_str)
    write_file(cpp_filepath,cpp_str)


def arg_line_handlde(args):

    arg_dict = collections.defaultdict(str)
    usage="usage %prog [option] arg1 arg2"
    parser = OptionParser(usage)
    parser.add_option("-s","--serverName",type="string",dest="serverName",help="serverName")
    parser.add_option("-c","--className",type="string",dest="className",help="className")
    parser.add_option("-p","--classPattern",type="int",default=0,dest="classPattern",help="class paterrn:0,common class;1,single pattern")

    if len(args) <=1:
        parser.print_help()
        exit()

    options,arg_list = parser.parse_args(args)

    if None == options.serverName:
        parser.error("must have serverName usage -h get help")
        # exit()

    if None == options.className:
        parser.error("must have className usage -h get help")
        # exit()

    # print(options)
    # print(arg_list)
    return options;

def main(args):

    options = arg_line_handlde(args)
    global serverName
    Usage = " ".join(("Usage: python/python3",args[0],"serverName","classname"))
    if len(args)<2:
        print(Usage)
        return
    serverName = options.serverName
    print(serverName)
    # classname = args[2]
    gen_class(options.className,options.classPattern)

if __name__ == '__main__':
    main(sys.argv)

