import os,re,json,sys

#范围定义在使用前需要替换
"""使用前替换范围定义"""
obj_range = "K0810:K0817999"
"""范围定义到此结束"""
#定义文件名
"""规定文件名"""
index = "38"
title = "计数原理与排列组合"
"""文件名到此结束"""

filename = index+"_"+title
outputfile = r"临时文件/"+filename+".tex"

template_file = r"模板文件/复习课目标模板.tex"


# 检查某一字符串是否在由,:的表达式给出的范围内
def within_range(string,list):
    flag = False
    for item in list:
        if string == item.strip():
            flag = True
            break
        elif ":" in item:
            start, end = item.split(":")
            if start <= string <= end:
                flag = True
                break
    return flag

# 读取课时目标数据库
with open(r"../题库0.3/LessonObj.json","r",encoding = "utf8") as f:
    database = f.read()
obj_dict = json.loads(database)

# 根据范围生成若干用于检查的闭区间范围
obj_range_list = obj_range.split(",")
output_string = ""

# 逐一选择目标, 并整合成表格的内容部分
for obj_id in obj_dict:
    if within_range(obj_id,obj_range_list):
        output_string += obj_id + " & " + obj_dict[obj_id]["content"] + " & " + r"\\ \hline" + "\n"

# 打开模板文件
with open(template_file,"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)

#预处理
exec_list = [("编号待替换",index),("标题待替换",title),("内容待替换",output_string)]
for command in exec_list:
    latex_raw = latex_raw.replace(command[0],command[1])

#输出到临时文件夹
with open(outputfile,"w",encoding = "utf8") as f:
    f.write(latex_raw)
print("开始编译目标pdf文件: ", outputfile)
os.system("xelatex -interaction=batchmode -output-directory=" + "临时文件" + " "+ outputfile)
print(os.system("xelatex -interaction=batchmode -output-directory=" + "临时文件" + " "+ outputfile))