require_relative 'instruction'

module GBRb::InstructionSet
  class Jump < Instruction
    def initialize condition, m=2, t_high=12, t_low=8, immediates=1
      super m, t_low, immediates
      @m_low = m
      @t_high = t_high
      @t_low = t_low
      @condition = condition.downcase.to_sym
    end

    def call r, mem, offset=0x00
      do_it = case @condition
              when :c
                r.carry_flag?
              when :none
                true
              when :nc
                not r.carry_flag?
              when :nz
                not r.zero_flag?
              when :z
                r.zero_flag?
              else
                false
              end

      if do_it
        @t = @t_high
        @m = @t_high / 4
        if @immediates == 0
          r.pc.store r.hl.read
        elsif @immediates == 1
          sign = (offset >> 7 == 1) ? :- : :+
          offset = ((offset ^ 0xff) + 1) & 0xff if sign == :-
          r.pc.store r.pc.read.public_send(sign, offset)
        else
          r.pc.store offset
        end
      else
        @t = @t_low
        @m = @m_low
      end
    end
  end
end
