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


import jingrow


def execute():
	jingrow.reload_pg("jcloud", "pagetype", "site")
	jingrow.reload_pg("jcloud", "pagetype", "account_request")
	jingrow.reload_pg("jcloud", "pagetype", "team")
	jingrow.reload_pg("jcloud", "pagetype", "team_member")

	user_accounts = jingrow.db.sql(
		"SELECT user, account_key, creation FROM `tabUser Account`", as_dict=1
	)
	enabled_users = [d.name for d in jingrow.db.get_all("User", {"enabled": 1}, ["name"])]

	users = [d.user for d in user_accounts]
	# create team for Administrator too
	if "Administrator" not in users:
		user_accounts.append(jingrow._dict({"user": "Administrator"}))

	for d in user_accounts:
		if not d.user:
			continue
		# create team
		team = jingrow.new_pg("Team")
		team.name = d.user
		team.append("team_members", {"user": d.user})
		team.enabled = d.user in enabled_users
		team.creation = d.creation
		team.modified = d.modified
		team.insert()

		# create account request
		if d.account_key:
			account_request = jingrow.new_pg("Account Request")
			account_request.request_key = d.account_key
			account_request.email = d.user
			account_request.team = d.user
			account_request.role = "Jcloud Admin"
			account_request.creation = d.creation
			account_request.insert()

		# update team in sites
		jingrow.db.set_value("Site", {"owner": d.user}, "team", team.name)

	jingrow.delete_pg_if_exists("PageType", "User Account")
