require_relative 'instruction'

module GBRb::InstructionSet
  class Call < Instruction
    def initialize condition, m=3, t_high=24, t_low=12, immediates=2
      @condition = condition
      @t_high = t_high
      @t_low = t_low
      @m_low = m
      super m, t_low, immediates
    end

    def call r, mem, addr
      condition_met = case @condition
                      when :c
                        r.carry_flag?
                      when :nc
                        not r.carry_flag?
                      when :nz
                        not r.zero_flag?
                      when :z
                        r.zero_flag?
                      when :none
                        true
                      else
                        false
                      end
      if condition_met
        r.sp.store r.sp.read - 2
        mem.write_word(r.sp.read, r.pc.read)
        r.pc.store addr
        @t = @t_high
        @m = @t_high / 4
      else
        @t = @t_low
        @m = @m_low
      end
    end
  end
end
