module Graffiti
  class CreateTag < 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 = :name
    attributes :name, :localize, :tag_scope, :instruction, :ldap_login, :description, :internal, :restricted, :persistent

    def save
      create_tag_payload = {}
      create_tag_payload["name"] = self.name
      create_tag_payload["tag_scope"] = self.tag_scope
      create_tag_payload["modifier_id"] = self.ldap_login
      create_tag_payload["description"] = self.description

      unless self.internal.blank?
        create_tag_payload["internal"] = self.class.booleanize(self.internal)
      end
      unless self.restricted.blank?
        create_tag_payload["restricted"] = self.class.booleanize(self.restricted)
      end
      unless self.persistent.blank?
        create_tag_payload["persistent"] = self.class.booleanize(self.persistent)
      end

      create_tag_response = post(
        "#{SERVICE_NAMESPACE}/CreateTag",
        headers: HEADERS,
        body: create_tag_payload.to_json
      )

      self.errors = create_tag_response.body["msg"] unless create_tag_response.success?
      return false unless create_tag_response.success?

      if self.localize == "1"
        create_task_payload = {}
        create_task_payload["id"] = create_tag_response.body["tag"]["id"]
        create_task_payload["instruction"] = self.instruction

        create_task_response = post(
          "#{LOCALIZATION_SERVICE_NAMESPACE}/CreateTagLocalizationTask",
          headers: HEADERS,
          body: create_task_payload.to_json
        )

        self.errors = "Tag Created, but Localization Task Failed: " + create_task_response.body["msg"] unless create_task_response.success?
        create_task_response.success?
      else
        return true
      end
    end
  end
end
