# Copyright (c) 2023, JINGROW
# For license information, please see license.txt

import json

import jingrow

from jcloud.agent import Agent
from jcloud.jcloud.report.server_stats.server_stats import get_servers


def execute(filters=None):
	jingrow.only_for("System Manager")
	columns = [
		{
			"fieldname": "server",
			"label": jingrow._("Server"),
			"fieldtype": "Dynamic Link",
			"options": "server_type",
			"width": 200,
		},
		{
			"fieldname": "server_type",
			"label": jingrow._("Server Type"),
			"fieldtype": "Link",
			"options": "PageType",
			"width": 140,
		},
		{
			"fieldname": "commit",
			"label": jingrow._("Commit"),
			"fieldtype": "Data",
			"width": 360,
		},
		{
			"fieldname": "status",
			"label": jingrow._("Status"),
			"fieldtype": "Long Text",
			"width": 100,
		},
		{
			"fieldname": "upstream",
			"label": jingrow._("Upstream"),
			"fieldtype": "Data",
			"width": 260,
		},
		{
			"fieldname": "show",
			"label": jingrow._("Show"),
			"fieldtype": "Long Text",
			"width": 100,
		},
		{
			"fieldname": "python",
			"label": jingrow._("Python Version"),
			"fieldtype": "Data",
			"width": 100,
		},
	]

	data = get_data(filters)
	return columns, data


def get_data(filters):
	rows = []
	for server in get_servers(filters):
		try:
			version = Agent(server.name, server.server_type).get_version()
			if version is None:
				version = {}
		except Exception:
			version = {}
		rows.append(
			{
				"server": server.name,
				"server_type": server.server_type,
				**version,
			}
		)
	return rows


@jingrow.whitelist()
def update_agent(filters):
	jingrow.only_for("System Manager")
	for server in get_servers(jingrow._dict(json.loads(filters))):
		server = jingrow.get_pg(server.server_type, server.name)
		server.update_agent_ansible()
