
class Passenger
  attr :name

  def initialize(name)
    @name = name
  end

  def book(flight)
    flight.book(self)
    booked(flight)
  rescue Exception => ex
    puts "can't book: #{ex.message}"
  end
  
  def booked(flight)
    puts "booked flight: #{flight}"
  end
end

class Flight
  attr :segments
  
  def initialize(*segments)
    @segments = segments
  end

  def getPrice()
    result = 0
    @segments.each { |s| result += s.getPrice() }
    return result
  end

  def book(passenger)
    @segments.each { |s| raise "#{@start}->#{@destination}: no seats available!" if (s.seats<1) }
    @segments.each { |s| s.book(passenger) }
  end

  def to_s()
    return @segments.collect{ |s| "\n   *#{s.start}->#{s.destination} (#{s.seats})" }.join()
  end
end

class Segment
  attr :start
  attr :destination
  attr :seats
  attr :date
  attr :price

  def initialize(start, destination, seats, date, price)
    @start = start
    @destination = destination
    @seats = seats
    @date = date
    @price = price
  end
  
  def getPrice()
    return @price
  end

  def getDistance()
    return DistanceManager.getDistance(@start, @destination)
  end

  def book(passenger)
    raise "#{@start}->#{@destination}: no seats available!" if (@seats<1)
    @seats -= 1
  end
end

class DistanceManager
  @@distances = Hash.new
  def DistanceManager.addDistance(from, to, distance)
    @@distances["#{from}#{to}"] = distance
    @@distances["#{to}#{from}"] = distance
  end
  def DistanceManager.getDistance(from, to)
    return (@@distances["#{from}#{to}"] or 0)
  end
end

DistanceManager.addDistance("Berlin", "Frankfurt", 400)
DistanceManager.addDistance("Berlin", "Hamburg",   150)
DistanceManager.addDistance("Frankfurt", "New York", 6200)
DistanceManager.addDistance("Frankfurt", "Atlanta", 6800)
DistanceManager.addDistance("Hamburg", "New York", 6100)

if __FILE__ == $0
  bf = Segment.new("Berlin", "Frankfurt", 100, nil, 500)
  fb = Segment.new("Frankfurt", "Berlin", 1, nil, 500)
  flight = Flight.new(bf, fb)
  puts flight.to_s
  p = Passenger.new("Bert")
  p.book(flight)
  puts flight.to_s
  
end
