module Dmca
  class Takedown < Dmca::Base

    self.primary_attribute = :notice_id
    attributes :notice_id, :content_id, :issuer_id, :url, :issue_time, :content_type, :title

    def self.all
      raise "Dmca::Takedown#all is unsupported"
    end

    def self.find_issued(user_id, window_start, window_end)
      proto_start = time_to_protobuf_timestamp(window_start)
      proto_end = time_to_protobuf_timestamp(window_end)

      resp = Takedown.client.struck_by(IssuerID: user_id, WindowStart: proto_start, WindowEnd: proto_end)

      raise resp.error.msg if resp.error

      paginate unpack_twirp_response(resp)
    end

    def self.find_received(user_id, window_start, window_end)
      proto_start = time_to_protobuf_timestamp(window_start)
      proto_end = time_to_protobuf_timestamp(window_end)

      resp = Takedown.client.struck_content(OwnerID: user_id, WindowStart: proto_start, WindowEnd: proto_end)

      raise resp.error.msg if resp.error

      paginate unpack_twirp_response(resp)
    end

    def save
      raise "Dmca::Takedown#save is unsupported"
    end

    def destroy
      raise "Dmca::Takedown#destroy is unsupported"
    end

    def self.time_to_protobuf_timestamp(time_str)
      parsed_time = Time.parse(time_str)

      Google::Protobuf::Timestamp.new(seconds: parsed_time.to_i)
    end

    def self.unpack_twirp_response(response)
      takedowns = response.data

      marshalled_takedowns = []

      takedowns.StruckContent.each do |takedown|
        marshalled_takedowns << Takedown.new(
          notice_id: takedown.NoticeID,
          content_id: takedown.ContentID,
          issuer_id: takedown.IssuerID,
          url: takedown.URL,
          issue_time: Time.at(takedown.IssueTime.seconds, takedown.IssueTime.nanos / 1000),
          content_type: takedown.ContentType,
          title: takedown.Title
        )
      end

      marshalled_takedowns
    end

  end
end
