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


import jingrow

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


@jingrow.whitelist()
def all():
	sites = frappe.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, doctype, tag):
	team = get_current_team()
	if frappe.db.exists("Press Tag", {"tag": tag, "doctype_name": doctype, "team": team}):
		frappe.throw(f"Tag '{tag}' already exists")
	tag = frappe.get_pg(
		{
			"doctype": "Press Tag",
			"doctype_name": doctype,
			"team": team,
			"tag": tag,
		}
	).insert(ignore_permissions=True)
	pg = frappe.get_pg(doctype, name).append("tags", {"tag": tag})
	pg.save()
	return tag


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


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