import os,re,time,json,sys

"""
模板文件目录下 题目清单.tex 文件不能缺失
"""

"""---设置题目列表---"""
#留空为编译全题库, a为读取文本文件中的题号筛选.txt文件生成题库
problems = r"""
14613,14615,14624,14950,14953,14956,14957,14961,14962,14947
"""
"""---设置题目列表结束---"""

"""---设置文件名---"""
#目录和文件的分隔务必用/
filename = "临时文件/高一区统考"
"""---设置文件名结束---"""

"""---设置是否需要解答题的空格---"""
spaceflag = True
"""---设置空格结束---"""
"""---设置是否提供学生版的答案---"""
answered = False
"""---设置是否提供答案结束---"""

#读取系统日期
current_time = time.localtime()
time_string = "_"+str(current_time.tm_year).zfill(4)+str(current_time.tm_mon).zfill(2)+str(current_time.tm_mday).zfill(2)

teachers_latex_file = filename + "_教师用" + time_string + ".tex"
students_latex_file = filename + "_学生用" + time_string + ".tex"

#生成数码列表, 逗号分隔每个区块, 区块内部用:表示整数闭区间
def generate_number_set(string,dict):
    string = re.sub(r"[\n\s]","",string)
    string_list = string.split(",")
    numbers_list = []
    for s in string_list:
        if not ":" in s:
            numbers_list.append(s.zfill(6))
        else:
            start,end = s.split(":")
            for ind in range(int(start),int(end)+1):
                numbers_list.append(str(ind).zfill(6))
    return numbers_list

#将正确率转化为含颜色代码的字符串
def get_color(value):
    value = float(value)
    if value>=0.5:
        (r,g,b)=(1,2-2*value,0)
    else:
        (r,g,b)=(2*value,1,0)
    return "{" + "%.3f" %(r) + "," + "%.3f" %(g) + ",0}"


def color_value(matchobj):
    value = matchobj.group(1)
    return "\t"+"\\fcolorbox[rgb]{0,0,0}"+ get_color(value) +"{" + value +"}"


#读取题库json文件并转化为字典
with open(r"../题库0.3/Problems.json","r",encoding = "utf8") as f:
    database = f.read()
pro_dict = json.loads(database)

#读取目标数据库json并转化为字典
with open(r"../题库0.3/LessonObj.json","r",encoding = "utf8") as f:
    database = f.read()
obj_dict = json.loads(database)

#生成题目列表
if problems.strip() == "":
    problem_list = list(pro_dict.keys())
elif problems.strip()[0] == "a":
    with open("文本文件/题号筛选.txt","r",encoding = "utf8") as f:
        problems = f.read()
    problem_list = [id for id in generate_number_set(problems.strip(),pro_dict) if id in pro_dict]
else:
    problem_list = [id for id in generate_number_set(problems.strip(),pro_dict) if id in pro_dict]

data_teachers = ""
data_students = ""
id_list = ""

#生成教师题目字符串与学生题目字符串, 准备替换至latex文件
for id in problem_list:
    problemset = pro_dict[id]
    problem = problemset["content"]
    solution = (problemset["solution"] if problemset["solution"] != "" else "暂无解答与提示")
    answer = "\\textcolor{red}{" + (problemset["ans"] if problemset["ans"] != "" else "暂无答案") + "}"
    remarks = (problemset["remark"] if problemset["remark"] != "" else "暂无备注")
    usages_list = problemset["usages"]
    if len(usages_list) > 0:
        usage = re.sub("\\t([\d]\.[\d]{0,10})",color_value,"\n\n".join(usages_list))
        usage = re.sub("[\\t ]([\d]\.[\d]{0,10})",color_value,usage)
    else:
        usage = "暂无使用记录"
    origin = (problemset["origin"] if problemset["origin"] != "" else "出处不详")
    objects = problemset["objs"]
    if len(objects) == 0:
        objects = "暂未关联目标\n\n"
    elif "KNONE" in [o.upper() for o in objects]:
        objects = "该题的考查目标不在目前的集合中\n\n"
    else:
        objects_string = ""
        for obj in objects:
            if not obj in obj_dict:
                objects_string = "目标" + obj + "有误\n\n"
                break
            else:
                objects_string += "\\textcolor{blue}{" + obj + "|" + obj_dict[obj]["content"] + "}\n\n"
        objects = objects_string
    space = ("" if problemset["space"] == "" or spaceflag == False else "\n"+r"\vspace*{"+problemset["space"]+"}\n")
    tags = ("|".join(problemset["tags"]) if len(problemset["origin"])>0 else "暂无标签")
    raw_string = "\\item " + "{\\tiny ("+id+")} "+problem
    teachers_string = raw_string.replace("\\tiny ","")+"\n\n关联目标:\n\n"+ objects + "\n\n标签: " + tags + "\n\n答案: "+answer + "\n\n" + "解答或提示: " + solution + "\n\n使用记录:\n\n"+ usage + "\n" + "\n\n备注: " + remarks + "\n\n出处: "+origin + "\n"
    if not answered:
        students_string = raw_string + space + "\n\n"
    else:
        students_string = raw_string + "\n\n答案: "+answer + "\n\n"
    data_teachers += teachers_string
    data_students += students_string



#替换latex文件的内容并编译
with open("模板文件/题目清单.txt","r",encoding = "utf8") as f:
    latex_raw = f.read()

#识别操作系统
if sys.platform != "win32":
    latex_raw = re.sub(r"fontset[\s]*=[\s]*none","fontset = fandol",latex_raw)
    latex_raw = re.sub(r"\\setCJKmainfont",r"% \\setCJKmainfont",latex_raw)

latex_raw = re.sub(r"\\tableofcontents","",latex_raw)

latex_teachers = latex_raw.replace("编译模板",data_teachers)
with open(teachers_latex_file,"w",encoding = "utf8") as f:
    f.write(latex_teachers)
print("开始编译教师版本pdf文件: ", teachers_latex_file)
d = re.search("/[^/]*$",teachers_latex_file).span()[0]
pdf_dir = teachers_latex_file[:d]
os.system("xelatex -interaction=batchmode -output-directory=" + pdf_dir + " "+ teachers_latex_file)
print(os.system("xelatex -interaction=batchmode -output-directory=" + pdf_dir + " "+ teachers_latex_file))

latex_students = latex_raw.replace("编译模板",data_students)
with open(students_latex_file,"w",encoding = "utf8") as f:
    f.write(latex_students)
print("开始编译学生版本pdf文件: ", students_latex_file)
d = re.search("/[^/]*$",students_latex_file).span()[0]
pdf_dir = students_latex_file[:d]
os.system("xelatex -interaction=batchmode -output-directory=" + pdf_dir + " "+ students_latex_file)
print(os.system("xelatex -interaction=batchmode -output-directory=" + pdf_dir + " "+ students_latex_file))
