# coding=UTF-8
import json
import os


def lanes_to_osm_type(file_path, out_put_dir, out_put_file_name, file_version):
    """
    根据车道线类型生成osm文件 track(路辙)：中心线；motorway（高速公路）：实线；construction施工）虚线；
                              path（小径）：特殊虚线；barrier->guard_rail:护栏；
                            secondary（次级道路）：护栏；unclassified：其他形状道路 ； tertiary（城市内部道路）：中心线 ；
                            road：没有类型道路；bridleway（马路）：牌子； cycleway（自行车道）：杆子；
                            living_street（生活街）：文字；crossing(十字路口)：扩展对象 water（水）->pond（池塘）: 箭头
                            trunk（城市快速），primary（主干道），footway（人行道）,service（小路），bus_guideway（公交车道）：预留
    :param file_path:
    :param out_put_dir:
    :param out_put_file_name:
    :param file_version:
    :return:
    """
    json_links = open(file_path, "r").read()
    links = json.loads(json_links)
    osm_nodes = ""
    osm_node_id = 1
    way = ""
    link_ids = [573005493, 3806742657, 823029431, 418428176, 1143143883, 2175007083, 1084968726, 2516719332, 2918911954,
                582426861, 591479954, 2039283277, 1070509361, 3178135721, 409222678, 972022516, 2951940446, 98930906,
                2155506425, 164013783, 102183896, 3008720974, 1124780627, 2995306097, 1539484224, 839297973, 2215430628,
                1426954136, 734986956, 141471217, 285060868, 3167089494, 1448505217, 1418844404, 1156551746, 3988891725,
                1344864049, 3349271506, 2905719958, 1273663389]
    used_items = {}
    for link, geolink in links.items():
        if long(link) in link_ids:
          used_items[link] = geolink
    
    def dist(a, b):
      return (abs(a[0] - b[0]) ** 2 + abs(a[1] - b[1])**2)**0.5

    for link1, geolink1 in used_items.items():
      target_items = []
      for index in range(len(geolink1)):
        if (index ==0 or index == len(geolink1) - 1):
          target = geolink1[index]
          min = 999999;
          minv = []
          for link2, geolink2 in used_items.items():
            if link1 != link2:
              for v in geolink2:
                d = dist(v, target)
                if(d < min):
                  min = d
                  minv = v
          target_items.append(minv) 
        else:
          target_items.append(geolink1[index])
      used_items[link1] = target_items
    
    for link, geolink in used_items.items():
        link_way = "	<way id=\"%s\" version=\"1\">\n" % (link)
        link_way += "		<tag k=\"highway\" v=\"trunk\"/>\n"
        link_way += "		<tag k=\"oneway\" v=\"yes\"/>\n"
        link_way += "		<tag k=\"name\" v=\"%s\"/>\n" % (link,)
        for node in geolink:
          osm_node = "	<node id=\"%s\" lat=\"%s\" lon=\"%s\" high=\"%s\" version=\"1\"/>\n" % (
              osm_node_id, node[1], node[0], node[2])
          osm_nodes += osm_node
          osm_way_node = "		<nd ref=\"%s\"/>\n" % (osm_node_id,)
          link_way += osm_way_node
          osm_node_id = osm_node_id + 1
        link_way += '    </way>\n'
        way += link_way
    osm_text = '<?xml version="1.0" encoding="utf-8"?>\n<osm generator="osmconvert 0.8.5" version="0.6">\n'
    osm_text = osm_text + osm_nodes + way
    osm_text += "</osm>"
    with open(out_put_dir + out_put_file_name, 'w')as f:
        f.write(osm_text)


file_path = "/home/nickfox/Desktop/sdmap/links_reference.json"
out_put_dir = "/home/nickfox/Desktop/sdmap/"
out_put_file_name = "sd_2053.osm"
file_version = "20200105"
lanes_to_osm_type(file_path, out_put_dir, out_put_file_name, file_version)
print "end"
exit()
