# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE
import getpass

import jingrow
from jingrow.geo.pagetype.country.country import import_country_and_currency
from jingrow.utils.password import update_password


def before_install():
	jingrow.reload_pg("core", "pagetype", "pagetype_state")
	jingrow.reload_pg("core", "pagetype", "pagefield")
	jingrow.reload_pg("core", "pagetype", "pageperm")
	jingrow.reload_pg("core", "pagetype", "pagetype_action")
	jingrow.reload_pg("core", "pagetype", "pagetype_link")
	jingrow.reload_pg("desk", "pagetype", "form_tour_step")
	jingrow.reload_pg("desk", "pagetype", "form_tour")
	jingrow.reload_pg("core", "pagetype", "pagetype")
	jingrow.clear_cache()


def after_install():
	create_user_type()
	install_basic_pgs()

	from jingrow.core.pagetype.file.utils import make_home_folder
	from jingrow.core.pagetype.language.language import sync_languages

	make_home_folder()
	import_country_and_currency()
	sync_languages()

	# save default print setting
	print_settings = jingrow.get_pg("Print Settings")
	print_settings.save()

	# set home page to app
	settings = jingrow.get_single("Website Settings")
	settings.home_page = "app"
	settings.save()

	# all roles to admin
	jingrow.get_pg("User", "Administrator").add_roles(*jingrow.get_all("Role", pluck="name"))

	# update admin password
	update_password("Administrator", get_admin_password())

	if not jingrow.conf.skip_setup_wizard:
		# only set home_page if the value doesn't exist in the db
		if not jingrow.db.get_default("desktop:home_page"):
			jingrow.db.set_default("desktop:home_page", "setup-wizard")
			jingrow.db.set_single_value("System Settings", "setup_complete", 0)

	# clear test log
	with open(jingrow.get_site_path(".test_log"), "w") as f:
		f.write("")

	add_standard_navbar_items()

	jingrow.db.commit()


def create_user_type():
	for user_type in ["System User", "Website User"]:
		if not jingrow.db.exists("User Type", user_type):
			jingrow.get_pg({"pagetype": "User Type", "name": user_type, "is_standard": 1}).insert(
				ignore_permissions=True
			)


def install_basic_pgs():
	# core users / roles
	install_pgs = [
		{
			"pagetype": "User",
			"name": "Administrator",
			"first_name": "Administrator",
			"email": "admin@example.com",
			"enabled": 1,
			"is_admin": 1,
			"roles": [{"role": "Administrator"}],
			"thread_notify": 0,
			"send_me_a_copy": 0,
		},
		{
			"pagetype": "User",
			"name": "Guest",
			"first_name": "Guest",
			"email": "guest@example.com",
			"enabled": 1,
			"is_guest": 1,
			"roles": [{"role": "Guest"}],
			"thread_notify": 0,
			"send_me_a_copy": 0,
		},
		{"pagetype": "Role", "role_name": "Report Manager"},
		{"pagetype": "Role", "role_name": "Translator"},
		{
			"pagetype": "Workflow State",
			"workflow_state_name": "Pending",
			"icon": "question-sign",
			"style": "",
		},
		{
			"pagetype": "Workflow State",
			"workflow_state_name": "Approved",
			"icon": "ok-sign",
			"style": "Success",
		},
		{
			"pagetype": "Workflow State",
			"workflow_state_name": "Rejected",
			"icon": "remove",
			"style": "Danger",
		},
		{"pagetype": "Workflow Action Master", "workflow_action_name": "Approve"},
		{"pagetype": "Workflow Action Master", "workflow_action_name": "Reject"},
		{"pagetype": "Workflow Action Master", "workflow_action_name": "Review"},
		{
			"pagetype": "Email Domain",
			"domain_name": "example.com",
			"email_id": "account@example.com",
			"password": "pass",
			"email_server": "imap.example.com",
			"use_imap": 1,
			"smtp_server": "smtp.example.com",
		},
		{
			"pagetype": "Email Account",
			"domain": "example.com",
			"email_id": "notifications@example.com",
			"default_outgoing": 1,
		},
		{
			"pagetype": "Email Account",
			"domain": "example.com",
			"email_id": "replies@example.com",
			"default_incoming": 1,
		},
	]

	for d in install_pgs:
		try:
			jingrow.get_pg(d).insert(ignore_if_duplicate=True)
		except jingrow.NameError:
			pass


def get_admin_password():
	def ask_admin_password():
		admin_password = getpass.getpass("Set Administrator password: ")
		admin_password2 = getpass.getpass("Re-enter Administrator password: ")
		if not admin_password == admin_password2:
			print("\nPasswords do not match")
			return ask_admin_password()
		return admin_password

	admin_password = jingrow.conf.get("admin_password")
	if not admin_password:
		return ask_admin_password()
	return admin_password


def before_tests():
	if len(jingrow.get_installed_apps()) > 1:
		# don't run before tests if any other app is installed
		return

	jingrow.db.truncate("Custom Field")
	jingrow.db.truncate("Event")

	jingrow.clear_cache()

	# complete setup if missing
	if not int(jingrow.db.get_single_value("System Settings", "setup_complete") or 0):
		complete_setup_wizard()

	jingrow.db.set_single_value("Website Settings", "disable_signup", 0)
	jingrow.db.commit()
	jingrow.clear_cache()


def complete_setup_wizard():
	from jingrow.desk.page.setup_wizard.setup_wizard import setup_complete

	setup_complete(
		{
			"language": "English",
			"email": "test@jingrow.com",
			"full_name": "Test User",
			"password": "test",
			"country": "United States",
			"timezone": "America/New_York",
			"currency": "USD",
		}
	)


def add_standard_navbar_items():
	navbar_settings = jingrow.get_single("Navbar Settings")

	# don't add settings/help options if they're already present
	if navbar_settings.settings_dropdown and navbar_settings.help_dropdown:
		return

	navbar_settings.settings_dropdown = []
	navbar_settings.help_dropdown = []

	for item in jingrow.get_hooks("standard_navbar_items"):
		navbar_settings.append("settings_dropdown", item)

	for item in jingrow.get_hooks("standard_help_items"):
		navbar_settings.append("help_dropdown", item)

	navbar_settings.save()
