from graph.topo_graph import *
import networkx as nx
import sqlite3


def graph_construct():
    """
    Reconstruct route graph for loading route and unload route.
    :return: Topo obj.
    """

    # 建立数据库连接
    conn = sqlite3.connect('test.db')
    c = conn.cursor()

    # 读取图节点
    cursor = c.execute("SELECT * FROM GRAPH_NODE")

    node_label = {}
    for row in cursor:
        node_label[row[1]] = row[2]

    print(node_label)

    # 读取图边
    cursor = c.execute("SELECT * FROM GRAPH_EDGE")

    # 新建装载及卸载路径拓扑图
    load_G = nx.Graph()

    unload_G = nx.Graph()

    for row in cursor:

        # 处理边包含路段
        lanes = row[5].split(" ")
        lane_info = {}

        for item in lanes:
            distance = session_postgre.query(Lane).filter_by(Id=item).first().Length
            lane_info[item] = list([distance, distance])

        # 重构卸载路径拓扑图
        if row[4] == 1:
            load_G.add_node(row[1], name=node_label[row[1]])
            load_G.add_node(row[2], name=node_label[row[2]])
            load_G.add_edge(str(row[1]), str(row[2]), real_distance=row[3], lane=lane_info)
        # 重构装载路径拓扑图
        else:
            unload_G.add_node(row[1], name=node_label[row[1]])
            unload_G.add_node(row[2], name=node_label[row[2]])
            unload_G.add_edge(str(row[1]), str(row[2]), real_distance=row[3], lane=lane_info)

    # 构建拓扑图并加载数据
    topo = Topo()
    topo.load_G = load_G
    topo.unload_G = unload_G
    topo.update_cross_nodes()
    topo.update_cross_bf_lanes()

    # print(topo.get_load_target_node_real('2e5d1f54-a6c9-4c93-89d1-2d9b69fd1e4f', '1010cbfe-b134-3ef1-91bb-d746241c975a'))

    return topo

    # print(topo.get_load_target_node_real("c016c06f-3134-63ad-fc99-842f556c6ed3", "1010cbfe-b134-3ef1-91bb-d746241c975a"))

# graph_construct()