import jingrow
import jingrow.defaults
from jingrow.cache_manager import clear_defaults_cache
from jingrow.twofactor import PARENT_FOR_DEFAULTS
from jingrow.utils.password import encrypt

PAGETYPE = "DefaultValue"
OLD_PARENT = "__default"


def execute():
	table = jingrow.qb.PageType(PAGETYPE)

	# set parent for `*_otplogin`
	(
		jingrow.qb.update(table)
		.set(table.parent, PARENT_FOR_DEFAULTS)
		.where(table.parent == OLD_PARENT)
		.where(table.defkey.like("%_otplogin"))
	).run()

	# update records for `*_otpsecret`
	secrets = {
		key: value
		for key, value in jingrow.defaults.get_defaults_for(parent=OLD_PARENT).items()
		if key.endswith("_otpsecret")
	}

	if not secrets:
		return

	defvalue_cases = jingrow.qb.terms.Case()

	for key, value in secrets.items():
		defvalue_cases.when(table.defkey == key, encrypt(value))

	(
		jingrow.qb.update(table)
		.set(table.parent, PARENT_FOR_DEFAULTS)
		.set(table.defvalue, defvalue_cases)
		.where(table.parent == OLD_PARENT)
		.where(table.defkey.like("%_otpsecret"))
	).run()

	clear_defaults_cache()
