module ContentTag
  class ChannelTag < ContentTag::Base
    SERVICE_NAMESPACE = "/twirp/code.justin.tv.discovery.graffiti.rpc.graffiti.Graffiti"
    HEADERS = { 'Content-Type' => 'application/json' }
    CHANNEL_CONTENT_TYPE = "LIVE_CHANNEL"
    VALID_STATES = %w[STATE_UNSET APPROVED REJECTED FLAGGED PENDING]
    # Point to your service endpoint & path
    # self.service_endpoint = "http://your-service-endpoint.twitch.tv"

    # Set your primary key attribute
    self.primary_attribute = :channel_id

    attributes :channel_id, :tag_name, :tag_id, :tags, :ldap_login

    validates :channel_id, :tag_id, presence: true

    def delete_channel_tag(tag_id)
      if tag_id == ""
        return from_errors("Empty Tag ID.")
      end

      body = JSON.dump(
        content_id: attributes["channel_id"],
        content_type: CHANNEL_CONTENT_TYPE,
        tag_ids: [tag_id]
      )

      response = post(
        "#{SERVICE_NAMESPACE}/DeleteContentTags",
        headers: HEADERS,
        body: body
      )

      self.errors.add(:base, response.body["msg"]) unless response.success?
      response.success?
    end

    def add_channel_tag(tag_id)
      if tag_id == ""
        return from_errors("Empty Tag ID.")
      end

      body = JSON.dump(
        content_id: attributes["channel_id"],
        content_type: CHANNEL_CONTENT_TYPE,
        tag_ids: [tag_id],
        modifier_id: attributes["ldap_login"]
      )

      response = post(
        "#{SERVICE_NAMESPACE}/CreateContentTags",
        headers: HEADERS,
        body: body
      )

      self.errors.add(:base, response.body["msg"]) unless response.success?
      response.success?
    end

    def self.find(id)
      if id == ""
        return from_errors("Please click on autocomplete results instead of manually enter the full names so it fetches the tag_id from Algolia.")
      end

      body = JSON.dump(
        content_id: id,
        content_type: CHANNEL_CONTENT_TYPE,
        states: VALID_STATES
      )

      response = post(
        "#{SERVICE_NAMESPACE}/GetContentTags",
        headers: HEADERS,
        body: body
      )

      return from_errors(response.body["msg"]) unless response.success?

      tags = response.body["tags"].nil? ? [] : response.body["tags"].select { |h| h["restricted"] == true }

      content_tag = from_attributes(
        :channel_id => response.body["content_id"],
        :tags => tags
      )

      content_tag
    end
  end
end
