# Copyright (c) 2024, JINGROW

from __future__ import unicode_literals

import jingrow

from jcloud.api.client import dashboard_whitelist


class TagHelpers:
	@dashboard_whitelist()
	def add_resource_tag(self, tag):
		team = jingrow.local.team().name
		existing_tags = [row.tag_name for row in self.tags]
		if tag in existing_tags:
			return

		if not jingrow.db.exists(
			"Jcloud Tag", {"tag": tag, "pagetype_name": self.pagetype, "team": team}
		):
			tag_pg = jingrow.new_pg(
				"Jcloud Tag", tag=tag, pagetype_name=self.pagetype, team=team
			).insert()
		else:
			tag_pg = jingrow.get_pg(
				"Jcloud Tag",
				{"tag": tag, "pagetype_name": self.pagetype, "team": team},
			)

		self.append("tags", {"tag": tag_pg.name})
		self.save()

	@dashboard_whitelist()
	def remove_resource_tag(self, tag):
		self.tags = [row for row in self.tags if row.tag_name != tag]
		self.save()
