import json
import time

from tqdm import tqdm

import ezdxf
import core
import drawer

from drawer import FanMainDrawer, ShaftDrawer, WindowDrawer, WindFlowDrawer, FanSystemDrawer

from drawer.GateDrawer import GateDrawer
from drawer.TunDrawer import TunDrawer
from drawer.WindBridgeDrawer import WindBridgeDrawer


def calculate_route_gap(graph_unit):
    tun_id = graph_unit['ntunid']
    tun = dict_tuns[tun_id]
    tun_from = tun['nfrom']['x'], tun['nfrom']['z']
    tun_to = tun['ntoid']['x'], tun['ntoid']['z']
    route = core.calculate_angle_with_x_axis(tun_from, tun_to)
    return route, tun['gap']


def calculate_route_middle(wind_flow_unit):

    path_start = wind_flow_unit[0]['x'], wind_flow_unit[0]['z']

    path_end = wind_flow_unit[-1]['x'], wind_flow_unit[-1]['z']

    path_middle = core.find_point_on_line(path_start, path_end, 1 / 2)
    route = core.calculate_angle_with_x_axis(path_start, path_end)
    return path_middle, route


def add_line_auxiliary(msp, from_, to_, color):
    msp.add_line(from_, to_, dxfattribs={'color': color})


if __name__ == '__main__':

    tmp_json = 'data/tunData.json'
    tmp_json2 = 'data/tunPath.json'
    with open(tmp_json, 'r', encoding='utf-8') as r:
        node_list = json.loads(r.read())

    tuns = node_list['tunsMap']

    with open(tmp_json2, 'r', encoding='utf-8') as r:
        node_list2 = json.loads(r.read())

    doc = ezdxf.new('R2000')
    doc.styles.add("LiberationSerif", font="LiberationSerif.ttf")
    msp = doc.modelspace()

    for tun in tqdm(tuns,desc='【巷道绘制中】'):

        tun_id = tun[0]
        tun_e = tun[1]

        if tun_e['tunType'] == '1':
            shaft_center = tun_e['nfrom']['x'], tun_e['nfrom']['z']
            sd = ShaftDrawer(msp, tun_e['fwidth'], shaft_center, 0, 42)
            sd.draw_shaft_drawer()
        else:
            vec1 = tun_e['vec12'][0]['x'], tun_e['vec12'][0]['z']
            vec2 = tun_e['vec12'][1]['x'], tun_e['vec12'][1]['z']
            vec3 = tun_e['vec34'][0]['x'], tun_e['vec34'][0]['z']
            vec4 = tun_e['vec34'][1]['x'], tun_e['vec34'][1]['z']
            color = core.get_color_by_layer(tun_e['nlayerid'])
            n_from = tun_e['nfrom']['x'], tun_e['nfrom']['z']
            n_to = tun_e['ntoid']['x'], tun_e['ntoid']['z']
            td = TunDrawer(msp, tun_e['nlayerid'], color, (vec1, vec2), (vec3, vec4), n_from, n_to)
            td.draw_tun()

            tun[1]['gap'] = core.min_distance_between_segments((vec1, vec2), (vec3, vec4))

    dict_tuns = {k: v for k, v in tuns}
    layers = node_list['layerMap']

    for layer in layers:
        windows = layer[1]['windows']
        for window in tqdm(windows,desc=f' 图层{layer[0]} 【风窗绘制中】'):
            point_c = window['x'], window['z']
            route, gap = calculate_route_gap(window)
            wd = WindowDrawer(msp, gap, point_c, route)
            wd.draw_window()
        gates = layer[1]['gates']
        for gate in tqdm(gates,desc=f'图层{layer[0]} 【风门绘制中】'):
            point_c = gate['x'], gate['z']
            route, gap = calculate_route_gap(gate)
            gd = GateDrawer(msp, gap, point_c, route)
            gd.draw_gate()
        fans = layer[1]['fans']
        for fan in tqdm(fans,desc=f'图层{layer[0]} 【风扇绘制中】'):
            if 'fanmain' in str(fan['strtype']):
                point_c = fan['x'], fan['z']
                route, gap = calculate_route_gap(fan)
                fmd = FanMainDrawer(msp, gap, point_c, route)
                fmd.draw_fan_main()
            if 'fansystem' in str(fan['strtype']):
                point_c = fan['x'], fan['z']
                route, gap = calculate_route_gap(fan)
                fsd = FanSystemDrawer(msp, gap, point_c, route)
                fsd.draw_fan_system()

    # path_lines = node_list2['pathLins']
    for line in node_list2:
        in_paths = line[1]['inPaths']
        for in_path in tqdm(in_paths,desc=f'图层{line[0]} 【进风方向绘制中】'):
            if len(in_path) != 0:
                path_middle, route = calculate_route_middle(in_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
                wfd.draw_wind_flow()
        no_paths = line[1]['noPaths']
        for no_path in tqdm(no_paths,desc=f'图层{line[0]} 【未指定方向绘制中】'):
            if len(no_path) != 0:
                path_middle, route = calculate_route_middle(no_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
                wfd.draw_wind_flow()
        out_paths = line[1]['outPaths']
        for out_path in tqdm(out_paths,desc=f'图层{line[0]} 【回风方向绘制中】'):
            if len(out_path) != 0:
                path_middle, route = calculate_route_middle(out_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)
                wfd.draw_wind_flow()
        use_paths = line[1]['usePaths']
        for use_path in tqdm(use_paths,desc=f'图层{line[0]} 【用风方向绘制中】'):
            if len(use_path) != 0:
                path_middle, route = calculate_route_middle(use_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)
                wfd.draw_wind_flow()
    with open('data/tunCross.json','r', encoding='utf-8') as r:
        node_list3 = json.loads(r.read())
    for layer in node_list3:
        cross_nodes = layer[1]['crossNodes']
        for cross_node in tqdm(cross_nodes,desc=f'图层{layer[0]} 【风桥绘制中】'):
            center = cross_node['crossPoint']['x'],-cross_node['crossPoint']['y']
            tun_node ={'ntunid':cross_node['tun1Id']}
            gap,route=calculate_route_gap(tun_node)
            tun1 = dict_tuns[cross_node['tun1Id']]
            wbd = WindBridgeDrawer(msp,center,cross_node['tun1Id'],cross_node['tun2Id'],layer[0],gap,route)
            wbd.draw_wind_bridge_drawer()
    a = time.time()
    doc.saveas(f'save/tuns{str(a)}.dxf')
