import tkinter as tk
import json
import math

def convert_coordinates_to_xy(latitude, longitude, 
                              scale, origin_x, origin_y):
  """
  経度緯度をXY座標に変換する。

  Args:
    latitude: 緯度
    longitude: 経度
    scale: 拡大率
    origin_x: 経度原点
    origin_y: 緯度原点

  Returns:
    x: X座標
    y: Y座標
  """
  x = 400 + (longitude - origin_x) * scale
  y = 300 - (latitude - origin_y) * scale
  return x, y

def load_railroad_data(geojson_file):
  """
  線路のGeoJSONデータを読み込む。

  Args:
    geojson_file: GeoJSONファイルのパス

  Returns:
    線路データのリスト
  """
  with open(geojson_file, 'r', encoding='utf-8') as f:
    data = json.load(f)
  railroads = []
  for feature in data['features']:
    coordinates = feature['geometry']['coordinates']
    railroad = []
    for coord in coordinates:
      railroad.append(coord)
    railroads.append(railroad)
  return railroads

def load_station_data(geojson_file):
  """
  駅のGeoJSONデータを読み込む。

  Args:
    geojson_file: GeoJSONファイルのパス

  Returns:
    駅データの辞書 (駅名: (x座標, y座標))
  """
  with open(geojson_file, 'r', encoding='utf-8') as f:
    data = json.load(f)
  stations = {}
  for feature in data['features']:
    station_name = feature['properties']['N02_005']
    coordinates = feature['geometry']['coordinates'][0]
    stations[station_name] = coordinates
  return stations

def count_stations_in_range(stations, origin_x, origin_y, 
                            scale, range_x, range_y):
  """
  指定された範囲内に存在する駅の数を数える。

  Args:
    stations: 駅データの辞書
    origin_x: 経度原点
    origin_y: 緯度原点
    scale: 拡大率
    range_x: 画面のX範囲
    range_y: 画面のY範囲

  Returns:
    範囲内に存在する駅の数
  """
  count = 0
  for station_name, coordinates in stations.items():
    x, y = convert_coordinates_to_xy(coordinates[1], coordinates[0],
                                     scale, origin_x, origin_y)
    if range_x[0] <= x <= range_x[1] and \
      range_y[0] <= y <= range_y[1]:
      count += 1
  return count

def create_railroad_lines(canvas, railroads, 
                          origin_x, origin_y, scale):
  """
  線路をCanvasに描画する。

  Args:
    canvas: Canvasウィジェット
    railroads: 線路データのリスト
    origin_x: 経度原点
    origin_y: 緯度原点
    scale: 拡大率
  """
  for railroad in railroads:
    for i in range(len(railroad) - 1):
      x1, y1 = convert_coordinates_to_xy(railroad[i][1], 
                                         railroad[i][0],
                                         scale, origin_x, origin_y)
      x2, y2 = convert_coordinates_to_xy(railroad[i+1][1], 
                                         railroad[i+1][0], 
                                         scale, origin_x, origin_y)
      canvas.create_line(x1, y1, x2, y2, fill='blue', width=1)

def create_stations(canvas, stations, origin_x, origin_y, 
                    scale, display_station_names=True):
  """
  駅をCanvasに描画する。

  Args:
    canvas: Canvasウィジェット
    stations: 駅データの辞書
    origin_x: 経度原点
    origin_y: 緯度原点
    scale: 拡大率
    display_station_names: 駅名を表示するかどうか
  """
  for station_name, coordinates in stations.items():
    x, y = convert_coordinates_to_xy(coordinates[1], 
                                     coordinates[0],
                                     scale, origin_x, origin_y)
    canvas.create_oval(x-2, y-2, x+2, y+2, 
                       fill='red', outline='black')
    if display_station_names:
      canvas.create_text(x, y, text=station_name)

def main():
  """
  メイン関数
  """
  root = tk.Tk()
  root.title("地図表示アプリ")
  root.geometry("800x600")

  canvas = tk.Canvas(root, width=800, height=600, bg='white')
  canvas.pack()

  # 初期設定
  origin_x = 139.44
  origin_y = 35.39
  scale = 35.0
  display_station_names = True

  # GeoJSONファイルの読み込み
  railroad_data = load_railroad_data("N02-22_RailroadSection.geojson")
  stations = load_station_data("N02-22_Station.geojson")

  def redraw():
    """
    画面を再描画する。
    """
    canvas.delete("all")
    range_x = [0, 800]
    range_y = [0, 600]

    num_stations = count_stations_in_range(stations, 
                                           origin_x, origin_y,
                                           scale, range_x, range_y)

    if num_stations > 300:
      display_station_names = False
    else:
      display_station_names = True

    create_railroad_lines(canvas, railroad_data, 
                          origin_x, origin_y, scale)
    create_stations(canvas, stations, origin_x, origin_y, 
                    scale, display_station_names)

  def on_mousewheel(event):
    """
    マウスホイールの処理。
    """
    nonlocal scale, origin_x, origin_y
    if event.delta > 0:  # スクロールアップ
      scale *= 2.0
    else:  # スクロールダウン
      scale /= 2.0
    redraw()

  def on_click(event):
    """
    画面をクリック時の処理。
    """
    nonlocal origin_x, origin_y
    x = event.x
    y = event.y

    # 画面座標から経度緯度を計算 (逆変換)
    latitude = origin_y - (y - 300) / scale
    longitude = origin_x + (x - 400) / scale

    origin_x = longitude
    origin_y = latitude
    redraw()

  # イベントハンドラの登録
  canvas.bind("<MouseWheel>", on_mousewheel)
  canvas.bind("<Button-1>", on_click)

  # 最初の描画
  redraw()

  root.mainloop()

if __name__ == "__main__":
  main()