# -*- coding: utf-8 -*-
# Copyright (c) 2020, JINGROW
# For license information, please see license.txt


import jingrow

from jcloud.api.site import protected
from jcloud.utils import get_current_team


@jingrow.whitelist()
def all():
	sites = jingrow.get_list(
		"Site",
		fields=["count(1) as count", "status"],
		order_by="creation desc",
		group_by="status",
	)
	return {"sites": sites}


@jingrow.whitelist()
@protected(["Site", "Release Group", "Server", "Database Server"])
def create_new_tag(name, pagetype, tag):
	team = get_current_team()
	if jingrow.db.exists("Jcloud Tag", {"tag": tag, "pagetype_name": pagetype, "team": team}):
		jingrow.throw(f"Tag '{tag}' already exists")
	tag = jingrow.get_pg(
		{
			"pagetype": "Jcloud Tag",
			"pagetype_name": pagetype,
			"team": team,
			"tag": tag,
		}
	).insert(ignore_permissions=True)
	pg = jingrow.get_pg(pagetype, name).append("tags", {"tag": tag})
	pg.save()
	return tag


@jingrow.whitelist()
@protected(["Site", "Release Group", "Server", "Database Server"])
def add_tag(name, pagetype, tag):
	pg = jingrow.get_pg(pagetype, name)
	pg.append("tags", {"tag": tag})
	pg.save()
	return tag


@jingrow.whitelist()
@protected(["Site", "Release Group", "Server", "Database Server"])
def remove_tag(name, pagetype, tag):
	pg = jingrow.get_pg(pagetype, name)
	pg.tags = [resource_tag for resource_tag in pg.tags if resource_tag.tag != tag]
	pg.save()
	return tag
