module Substwirp
  class ResubTokens < Substwirp::Base
    attributes :chat_notification_token, :used_chat_tokens, :owner, :channel, :tenure, :method_val, :streak_value, :streak_shared, :custom_message_text, :custom_message_shared, :product, :tier, :allow_replay, :created_at, :updated_at

    def self.get_available_token(user_id, channel_id)
      response = twirp_client.get_user_channel_chat_notification_token(
        channel_id: channel_id,
        user_id: user_id
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data)
    end

    def self.get_all_used_tokens(user_id, channel_id)
      response = twirp_client.get_all_used_chat_notification_tokens(
        channel_id: channel_id,
        user_id: user_id
      )
      raise response.error.msg if response.error

      self.unpack_twirp_response(response)
    end

    def self.allow_replay(owner_id, channel_id, tenure)
      response = twirp_client.allow_replay_for_last_used_chat_notification_token(
        owner_id: owner_id,
        channel_id: channel_id,
        tenure: tenure,
        method: "cumulative"
      )
      raise response.error.msg if response.error

      response.data
    end

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

      marshalled_resub_tokens = []

      tokens.used_chat_tokens.each do |token|
        marshalled_resub_tokens << ResubTokens.new(
          method_val: token["method"],
          owner: token.owner,
          tenure: token.tenure,
          channel: token.channel,
          streak_value: token.streak_value,
          streak_shared: token.streak_shared,
          custom_message_text: token.custom_message_text,
          custom_message_shared: token.custom_message_shared,
          product: token.product,
          tier: token.tier,
          allow_replay: token.allow_replay,
          updated_at: Time.at(token.updated_at.seconds, token.updated_at.nanos / 1000),
          created_at: Time.at(token.created_at.seconds, token.created_at.nanos / 1000)
        )
      end

      return marshalled_resub_tokens
    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
  end
end
