class Handler
  def initialize(first_msg)
    @type, @seq, @limit = msg.type, msg.seq, msg.limit
    first_msg.ack!
  end

  def upto(limit)
    if limit > @limit
      raise BadMessage, "Message sequence too short"
    end
    
    loop do
      msg = Message.get

      if msg.type != @type ||
            msg.limit != @limit ||
            msg.seq > limit
        raise BadMessage, "Invalid message continuation"
      end

      yield msg
    end
  end

  def dispatch
    raise NotImplementedError
  end
end

class Protocol
  def initialize(handlers)
    @handlers = handlers
  end

  def dispatch
    loop { dispatch_one }
  end

  def dispatch_one
    msg = Message.get
    return unless msg.seq == 0

    @handlers.find do |handler|
      handler.accept?(msg)
    end.new(msg).dispatch
  rescue e
    # nothing;
    # or: debug_trace(e)
  end
end

class FirmwareFlashHandler
  UNLOCK_KEY = ByteArray("\x00" * 64)

  def initialize(first_msg)
    unless first_msg.payload == UNLOCK_KEY
      raise BadMessage, "Invalid unlock key"
    end

    super
  end

  def dispatch
    flasher = FirmwareFlasher.new

    upto(@limit - 1) do |msg|
      flasher.process(msg.payload)
      msg.ack!
    end

    upto(@limit) do |msg|
      flasher.verify_hash(msg.payload)
      msg.ack!
    end
  end
end

Protocol.new([
  FirmwareFlashHandler
]).dispatch