#!/usr/bin/env ruby

require 'gtk2'
require 'date'
include Math

GM = 1.32712438e20
AU = 1.4959787e11
$namePlanet = {
  "Mercury" => "水星",
  "Venus"   => "金星",
  "Earth"   => "地球",
  "Mars"    => "火星",
  "Jupiter" => "木星",
  "Saturn"  => "土星",
  "Uranus"  => "天王星",
  "Neptune" => "海王星",
  "Pluto"   => "冥王星"
}

def getX(a,e,incl,node,peri,mm,d)
  n = sqrt(GM / (a * AU * a * AU * a * AU)) * 24.0 * 3600.0
  mm *= (PI / 180.0)
  mm += n * d
  incl *= (PI / 180.0)
  node *= (PI / 180.0)
  peri *= (PI / 180.0)
  ee = mm - e * sin(mm)
  for i in 1..6 do
    ee = ee - (ee - e * sin(ee) - mm) / (1.0 - e * cos(ee))
  end
  r = a * (1.0 - e * cos(ee))
  x = a * ((cos(node) * cos(peri) - sin(node) * cos(incl) * sin(peri)) * (cos(ee) - e) - (cos(node) * sin(peri) + sin(node) * cos(incl) * cos(peri)) * (sqrt(1.0 - e * e) * sin(ee)))
  y = a * ((sin(node) * cos(peri) + cos(node) * cos(incl) * sin(peri)) * (cos(ee) - e) - (sin(node) * sin(peri) - cos(node) * cos(incl) * cos(peri)) * (sqrt(1.0 - e * e) * sin(ee)))
  z = a * (sin(incl) * sin(peri) * (cos(ee) - e) + sin(incl) * cos(peri) * (sqrt(1.0 - e * e) * sin(ee)))
  return x,y,z
end

$planet = Hash.new
def getPlanetElements()
  open("p_elem_t1.txt","r") do |f|
    while line = f.gets do
      line.chop!
      line.gsub!(/ +/," ")
      line.gsub!(/EM Bary/,"Earth")
      a = line.split(" ")
      if a.size == 7
        p = $namePlanet[a[0]]
        if p == nil
          p = a[0]
        end
        $planet[p] = [
          a[1].to_f(),  # 0: a [AU]
          a[2].to_f(),  # 1: e
          a[3].to_f(),  # 2: I [deg]
          a[6].to_f(),  # 3: long.node. [deg] Ω
          a[5].to_f(),  # 4: long.peri. [deg] ω
          a[4].to_f() - a[5].to_f() - a[6].to_f() # 5: M [deg]
        ]
      end
    end
  end
end

$asteroidElements = []
def getAsteroidElements()
  i = 0
  open("ELEMENTS.NUMBR","r") do |f|
    while line = f.gets do
      i += 1
      if i >= 3
        line.chop!
        $asteroidElements.push [
          line[31..40].to_f(),  # 0: a [AU]
          line[42..51].to_f(),  # 1: e
          line[53..61].to_f(),  # 2: I [deg]
          line[73..81].to_f(),  # 3: long.node. [deg] Ω
          line[63..71].to_f(),  # 4: long.peri. [deg] ω
          line[83..93].to_f(),  # 5: M [deg]
          line[25..29].to_f()   # 6: Epoch
        ]
      end
    end
  end
  num = $asteroidElements.size
  i = 0
  open("ELEMENTS.UNNUM","r") do |f|
    while line = f.gets do
      i += 1
      if i >= 3
        line.chop!
        $asteroidElements.push [
          line[18..28].to_f(),  # 0: a [AU]
          line[30..39].to_f(),  # 1: e
          line[41..49].to_f(),  # 2: I [deg]
          line[61..69].to_f(),  # 3: long.node. [deg] Ω
          line[51..59].to_f(),  # 4: long.peri. [deg] ω
          line[71..81].to_f(),  # 5: M [deg]
          line[12..16].to_f()   # 6: Epoch
        ]
      end
    end
  end
#  puts "番号付きの小惑星：#{num}個"
#  puts "番号無しの小惑星：#{$asteroidElements.size - num}個"
#  puts "合計　　　　　　：#{$asteroidElements.size}個"
end

class EntryWindow < Gtk::Window
  def initialize(parent,t)
    super()
    set_title("表示日時の設定")
    set_border_width(10)
    set_default_size(380, 160)
    vbox = Gtk::VBox.new(false, 5)
    add(vbox)
    hbox = Gtk::HBox.new(false, 5)
    vbox.pack_start(hbox, false, false, 0)
    label = Gtk::Label.new("日時")
    hbox.pack_start(label, false, false, 0)
    subbox = Gtk::HBox.new(false, 1)
    hbox.pack_start(subbox, false, false)
    entry_duedate_yr = Gtk::Entry.new
    entry_duedate_yr.set_text("#{t.year}")
    entry_duedate_yr.set_max_length(4)
    entry_duedate_yr.set_width_chars(4)
    entry_duedate_yr.set_xalign(1)
    subbox.pack_start(entry_duedate_yr, false, false, 0)
    label = Gtk::Label.new("年")
    subbox.pack_start(label, false, false, 0)
    entry_duedate_mo = Gtk::Entry.new
    entry_duedate_mo.set_text("#{format("%02d",t.mon)}")
    entry_duedate_mo.set_max_length(2)
    entry_duedate_mo.set_width_chars(2)
    entry_duedate_mo.set_xalign(1)
    subbox.pack_start(entry_duedate_mo, false, false, 0)
    label = Gtk::Label.new("月")
    subbox.pack_start(label, false, false, 0)
    entry_duedate_day = Gtk::Entry.new
    entry_duedate_day.set_text("#{format("%02d",t.day)}")
    entry_duedate_day.set_max_length(2)
    entry_duedate_day.set_width_chars(2)
    entry_duedate_day.set_xalign(1)
    subbox.pack_start(entry_duedate_day, false, false, 0)
    label = Gtk::Label.new("日")
    subbox.pack_start(label, false, false, 0)
    bbox = Gtk::HButtonBox.new
    bbox.layout_style = Gtk::ButtonBox::END
    bbox.spacing = 10
    vbox.pack_start(bbox, false, false, 0)
    button = Gtk::Button.new("設定")
    button.signal_connect("clicked"){
      t = Date.new(entry_duedate_yr.text.to_i,entry_duedate_mo.text.to_i,entry_duedate_day.text.to_i)
      parent.setDate(t)
      destroy()
      parent.draw()
    }
    bbox.add(button)
    button = Gtk::Button.new(Gtk::Stock::CANCEL)
    button.signal_connect("clicked"){
      destroy()
    }
    bbox.add(button)
  end
end


class Asteroid < Gtk::VBox
  def initialize(parent)
    @parent = parent
    super()
    @t = Date.today
#    @t = Date.new(2109,6,18)

    @red = Gdk::Color.parse("#FF0000")
    @blue = Gdk::Color.parse("#0000FF")
    @black = Gdk::Color.parse("#000000")
    @colormap = Gdk::Colormap.system
    @colormap.alloc_color(@red, false, true)
    @colormap.alloc_color(@blue, false, true)
    @colormap.alloc_color(@black, false, true)
    item_factory = Gtk::ItemFactory.new(Gtk::ItemFactory::TYPE_MENU_BAR, "<main>",nil)
    item_factory.create_item("/編集", Gtk::ItemFactory::BRANCH)
    item_factory.create_item("/編集/日時の設定", Gtk::ItemFactory::ITEM){|d,i| selectDate()}
    @menubar = item_factory.get_widget("<main>")   # 関数呼び出し側にメニューを返す
    pack_start(@menubar, false, true, 0)
    @hbox = Gtk::HBox.new(false, spacing)
    pack_start(@hbox)
    @scrolled_window = Gtk::ScrolledWindow.new
    @scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
    @box = Gtk::EventBox.new
    @hbox.pack_start(@box, true, true, 0)
    set_border_width(@pad = 2)
    set_size_request((@width = 48)+(@pad*2), (@height = 48)+(@pad*2))
    signal_connect("expose_event") {|w, e| draw()}
    @menubar.show()
    @hbox.show()
    @box.show()
    @scrolled_window.show()
    show()
  end
  def selectDate()
    ew = EntryWindow.new(self,@t)
    ew.show_all # 入力用ウィンドウの表示
  end
  def setDate(t)
    @t = t
  end
  def draw()
    if @oldT != nil
      if @oldT == @t
        return
      end
    end
    @oldT = @t
    draw = @box.window
    x, y, width, height, depth = draw.geometry
    x0 = width / 2.0
    y0 = height / 2.0
    k = x0
    if y0 < k
      k = y0
    end
    k /= 6.0
    draw.clear
    gc = Gdk::GC.new(draw)
    l = create_pango_layout
    l.font_description=Pango::FontDescription.new("Sans 12")
    l.set_text("#{@t.year}/#{format("%02d",@t.mon)}/#{format("%02d",@t.day)}")
    draw.draw_layout(gc, 0, 0, l)
    gc.set_foreground(@red)
    draw.draw_arc(gc, true, x0 - 4, y0 - 4, 8, 8,0,64*360)
    l.set_text("太陽")
    draw.draw_layout(gc, x0, y0, l)
    gc.set_foreground(@blue)
    $planet.each do |p,e|
      l.set_text(p)
      x,y,z = getX(e[0],e[1],e[2],e[3],e[4],e[5],@t.ajd().to_f()-2451545.0)
      draw.draw_arc(gc, true, k * x + x0 - 4, - k * y + y0 - 4, 8, 8,0,64*360)
#      draw.draw_arc(gc, true, k * x + x0 - 4, - k * z + y0 - 4, 8, 8,0,64*360)
      draw.draw_layout(gc,  k * x + x0, - k * y + y0, l)
#      draw.draw_layout(gc,  k * x + x0, - k * z + y0, l)
    end
    gc.set_foreground(@black)
    $asteroidElements.each do |e|
      x,y,z = getX(e[0],e[1],e[2],e[3],e[4],e[5],@t.amjd().to_f() - e[6])
      draw.draw_point(gc, k * x + x0, - k * y + y0)
#      draw.draw_point(gc, k * x + x0, - k * z + y0)
    end
  end
end


if $0 == __FILE__

WINDOW_SIZE = [640, 480]

class Viewer < Gtk::Window
  def initialize()
    super()
    set_title("Asteroid")
    signal_connect("delete_event") { |i,a| Gtk::main_quit }
    set_default_size(*WINDOW_SIZE)
    add(Asteroid.new(self))
    show()
  end
end

Gtk.init()

getPlanetElements()
getAsteroidElements()
$view = Viewer.new
$view.show

Gtk.main()
  
end


