module Chronobreak
  class Tenure < Chronobreak::Base

    attributes :owner_id, :item_id, :domain, :streak_value, :tenure_value, :tenure_method, :start, :end, :elapsedDays, :daysRemaining, :grants, :tenures

    TENURE_METHODS = {
      CUMULATIVE: 0,
      STREAK: 1
    }
    SUB_DOMAIN = 'subChannel'
    OVERRIDE = 'OVERRIDE'

    def self.find_tenure(user_id, channel_id, domain, tenure_method)
      response = twirp_client.read_tenure(
        owner_id: user_id,
        item_id: channel_id,
        domain: domain,
        tenure_method: tenure_method,
        tenure_date: time_to_protobuf_timestamp(Time.now.to_s)
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data)
    end

    def self.find_tenures(user_id, channel_id, domain, tenure_method)
      response = twirp_client.read_tenures(
        owner_id: user_id,
        item_id: channel_id,
        domain: domain,
        tenure_method: tenure_method
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data)
    end

    def self.find_grants(user_id, channel_id, domain)
      response = twirp_client.read_grants(
        owner_id: user_id,
        item_id: channel_id,
        domain: domain
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data)
    end

    def self.upsert_override_grant(user_id, channel_id, start_date, end_date)
      response = twirp_client.upsert_grant(
        owner_id: user_id,
        item_id: channel_id,
        origin_id: Time.now.to_s,
        domain: SUB_DOMAIN,
        start: time_to_protobuf_timestamp(start_date),
        end: time_to_protobuf_timestamp(end_date),
        action: OVERRIDE
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data)
    end

    def self.delete_override_grant(user_id, channel_id, origin_id, domain)
      response = twirp_client.delete_override_grant(
        owner_id: user_id,
        item_id: channel_id,
        origin_id: origin_id,
        domain: domain
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data)
    end

    def self.preview_tenure_with_grant(user_id, channel_id, start_date, end_date)
      response = twirp_client.preview_tenure(
        owner_id: user_id,
        item_id: channel_id,
        domain: "subChannel",
        start: time_to_protobuf_timestamp(start_date),
        end: time_to_protobuf_timestamp(end_date),
        tenure_date: time_to_protobuf_timestamp(Time.now.to_s)
      )
      raise response.error.msg if response.error

      self.from_twirp_object(response.data)
    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
