import json
import os
import copy

def read_json(file_path):
    with open(file_path, 'r') as file:
        return json.load(file)

def set_gid_in_layer(layer, x, y, gid):
    width = layer['width']
    index = (y+2) * width + x
    if index < len(layer['data']):
        layer['data'][index] = gid

def update_tiled_json(source_json, tiled_template):
    for item in source_json['LevelData']:
        x, y, z = item['X'], item['Y'], item['Z']
        if z < 10:
            layer_name = f"Tile_{z}"
            layer = next((l for l in tiled_template['layers'] if l['name'] == layer_name), None)
            if layer:
                set_gid_in_layer(layer, x, y, 1)

    marks_layer = next((l for l in tiled_template['layers'] if l['name'] == "Marks"), None)
    if marks_layer:
        for item in source_json['StackData']:
            x, y = item['X'], item['Y']
            set_gid_in_layer(marks_layer, x, y, 100)

    return tiled_template

def write_json(data, file_path):
    with open(file_path, 'w+') as file:
        json.dump(data, file, indent=4)

def process_files(source_dir, target_dir, template_file):
    tiled_template = read_json(template_file)

    for file_name in os.listdir(source_dir):
        if file_name.endswith('.json'):
            template = copy.deepcopy(tiled_template)
            source_file = os.path.join(source_dir, file_name)
            source_data = read_json(source_file)
            updated_tiled_data = update_tiled_json(source_data, template)

            base_name = os.path.splitext(file_name)[0]
            output_file = os.path.join(target_dir, f"tf_{base_name}.json")
            write_json(updated_tiled_data, output_file)

# 获取当前工作目录
current_dir = os.getcwd()
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

# Example usage
source_dir = '/Users/xulianxin/Documents/develop/game/TileMatch/TileManor.Lv/TileFamily/level_data2'
target_dir = '../tf_templates'
template_file = '../templates/0000-template.json'
process_files(source_dir, target_dir, template_file)

os.chdir(current_dir)