class ExchangeData
  attr_accessor :max_three_ways, :max_transplants
  attr_accessor :error_message

  attr_reader :include_all_cycles
  attr_reader :all_cycles
  attr_reader :total_three_cycles
  attr_reader :total_two_cycles
  
  def initialize(exchange_data, operation)
    @exchange_data = exchange_data
    @operation = operation

    if(check_for_error(exchange_data))
      return
    end

    get_all_cycles
    get_matchings

    @total_two_cycles = get_total_num_cycles(2)
    @total_three_cycles = get_total_num_cycles(3)
	end

  def get_total_num_cycles(size)
	total = 0
    @all_cycles.each_key { |group_id| total += @all_cycles[group_id].patients.size == size ? 1 : 0}
	total
  end

  def get_all_cycles
    @all_cycles = {}
    @exchange_data['output']['all_cycles'].each do |id, cycle|
	  id_as_int = Integer(id)
      @all_cycles[id_as_int] = CycleEntry.new(id_as_int, cycle);
    end
  end

  def exchanges
    @all_exchanges
  end

  def get_matchings
    @all_exchanges = [];
    for data in @exchange_data['output']['exchange_data']
      @all_exchanges << Exchange.new(data['description'], data['weight'], data['two_way_exchanges'],
                                     data['three_way_exchanges'], data['total_transplants'],
                                     get_cycle_entries(data['exchanges']))
    end
  end

  def get_cycle_entries(exchanges)
    entries = []
    exchanges.each do |element|
      entries << @all_cycles[element]
    end
    entries
  end

  def error?
    @errored
  end
  
  private
  def check_for_error(data)
    if(data.key? 'error')
      @errored = true
      @error_message = data['error']
    end
    @errored = false
  end
end
