module BlockedIps
  class Item < BlockedIps::Base
    SERVICE_NAMESPACE = "/twirp/code.justin.tv.safety.ipblock.rpc.RPCService"

    self.service_endpoint = Settings.ipblock.endpoint

    self.primary_attribute = :ip

    attributes :ip, :duration, :is_blocked

    def self.find(item, options = {})
      req_options = { headers: {'Content-Type' => 'application/json'}, body: item.to_json }
      response = post "#{SERVICE_NAMESPACE}/IsBlockedIP", req_options

      if response.success?
        from_attributes(item.merge(response.body))
      else
        from_errors(response.body["msg"])
      end
    end

    def save
      req_options = { headers: {'Content-Type' => 'application/json'}, body: to_json }
      response = post "#{SERVICE_NAMESPACE}/BlockIP", req_options

      self.errors = response.body["msg"] unless response.success?

      response.success?
    end

    def destroy
      req_options = { headers: {'Content-Type' => 'application/json'}, body: to_json }
      response = post "#{SERVICE_NAMESPACE}/UnblockIP", req_options

      self.errors = response.body["msg"] unless response.success?

      response.success?
    end
  end
end
