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


import jingrow
from jingrow.model.page import Page
from jingrow.utils import cstr

from jcloud.api.client import is_owned_by_team
from jcloud.utils import poly_get_pagetype


class AnsiblePlay(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		changed: DF.Int
		duration: DF.Time | None
		end: DF.Datetime | None
		failures: DF.Int
		ignored: DF.Int
		ok: DF.Int
		play: DF.Data
		playbook: DF.Data
		rescued: DF.Int
		server: DF.DynamicLink
		server_type: DF.Link
		skipped: DF.Int
		start: DF.Datetime | None
		status: DF.Literal["Pending", "Running", "Success", "Failure"]
		unreachable: DF.Int
		variables: DF.Code
	# end: auto-generated types

	dashboard_fields = [
		"name",
		"creation",
		"status",
		"start",
		"end",
		"duration",
		"server",
		"play",
	]

	@staticmethod
	def get_list_query(query, filters=None, **list_args):
		server = cstr(filters.get("server", ""))

		if not server:
			jingrow.throw("不允许", jingrow.PermissionError)

		if server.startswith("["):
			servers = jingrow.parse_json(server.replace("'", '"'))[1]

			for server in servers:
				pagetype = poly_get_pagetype(["Server", "Database Server"], server)
				is_owned_by_team(pagetype, server, raise_exception=True)
		else:
			pagetype = poly_get_pagetype(["Server", "Database Server"], server)
			is_owned_by_team(pagetype, server, raise_exception=True)

		results = query.run(as_dict=1)
		return results

	def get_pg(self, pg):
		pg["tasks"] = jingrow.get_all(
			"Ansible Task",
			filters={"play": self.name},
			fields=["task", "status", "start", "end", "duration"],
			order_by="creation",
		)

		return pg

	def on_trash(self):
		jingrow.db.delete("Ansible Task", {"play": self.name})
