module Graffiti
  class EditTag < Graffiti::Base
    SERVICE_NAMESPACE = "/twirp/code.justin.tv.discovery.graffiti.rpc.graffiti.Graffiti"
    LOCALIZATION_SERVICE_NAMESPACE = "/twirp/code.justin.tv.discovery.graffiti.rpc.graffitilocalization.GraffitiLocalization"
    HEADERS = { 'Content-Type' => 'application/json' }

    self.primary_attribute = :id

    attributes :id, :name, :state, :scope, :internal, :ldap_login, :description, :localize, :restricted, :persistent

    LOCALES.each do |locale|
      attributes(locale)
    end

    DESCRIPTION_LOCALES.each do |description_locale|
      attributes(description_locale)
    end

    def self.find(id, _options = {})
      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(
        id: id
      )

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

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

      tag = from_attributes(
        :id => response.body["tag"]["id"],
        :name => response.body["tag"]["name"],
        :state => response.body["tag"]["state"],
        :scope => response.body["tag"]["tag_scope"],
        :internal => response.body["tag"]["internal"],
        :restricted => response.body["tag"]["restricted"],
        :persistent => response.body["tag"]["persistent"]
      )
      if response.body["tag"]["internal"].nil?
        tag.internal = false
      end
      if response.body["tag"]["restricted"].nil?
        tag.restricted = false
      end
      if response.body["tag"]["persistent"].nil?
        tag.persistent = false
      end
      if response.body["tag"]["state"].nil?
        tag.state = "APPROVED"
      end
      if response.body["tag"]["tag_scope"].nil?
        tag.scope = "SCOPE_ALL"
      end

      localizations = response.body["tag"]["localizations"]
      LOCALES.each_with_object(tag) { |locale, memo| memo.send("#{locale}=", localizations[locale.to_s.sub!('_', '-')]) }

      description_localizations = response.body["tag"]["description_localizations"]
      DESCRIPTION_LOCALES.each_with_object(tag) { |description_locale, memo| memo.send("#{description_locale}=", description_localizations[description_locale.to_s.last(5).sub!('_', '-')]) } unless description_localizations.nil?
      tag
    end

    def create_localization_task(id)
      create_task_payload = {}
      create_task_payload["id"] = id
      create_task_payload["instruction"] = ""

      create_task_response = post(
        "#{LOCALIZATION_SERVICE_NAMESPACE}/CreateTagLocalizationTask",
        headers: HEADERS,
        body: create_task_payload.to_json
      )
      self.errors = "Localization Task Failed: " + create_task_response.body["msg"] unless create_task_response.success?
      return create_task_response.success?
    end

    def save
      if self.localize == "1"
        return false unless create_localization_task(id) == true
      end

      localizations = {}
      LOCALES.each_with_object(localizations) { |locale, memo| memo[locale.to_s.sub!('_', '-')] = self.instance_variable_get("@#{locale}") unless self.instance_variable_get("@#{locale}").blank? }

      description_localizations = {}
      DESCRIPTION_LOCALES.each_with_object(description_localizations) { |description_locale, memo| memo[description_locale.to_s.last(5).sub!('_', '-')] = self.instance_variable_get("@#{description_locale}") unless self.instance_variable_get("@#{description_locale}").blank? }

      payload = {}

      payload["id"] = id
      payload["modifier_id"] = self.ldap_login
      unless self.state.blank?
        payload["state"] = self.state
      end
      unless self.name.blank?
        payload["name"] = self.name
      end
      unless self.scope.blank?
        payload["tag_scope"] = self.scope
      end
      unless self.internal.blank?
        payload['internal'] = self.class.booleanize(self.internal)
      end
      unless self.restricted.blank?
        payload['restricted'] = self.class.booleanize(self.restricted)
      end
      unless self.persistent.blank?
        payload['persistent'] = self.class.booleanize(self.persistent)
      end
      payload["localizations"] = localizations
      payload["description_localizations"] = description_localizations
      payload['ipr_set'] = true

      response = post(
        "#{SERVICE_NAMESPACE}/UpdateTag",
        headers: HEADERS,
        body: payload.to_json
      )
      self.errors = response.body["msg"] unless response.success?
      response.success?
    end
  end
end
