# -*- coding: utf-8 -*-
# plugin.video.alkoflix
# resources/lib/modules/parental_pin_backup.py

from datetime import datetime

from modules import kodi_utils
from modules.alkopastes_api import has_user_api_key, _request, _paste_code, _mask_code

BACKUP_SETTING = 'parental.pin_backup_code'
BACKUP_TITLE = 'alkoFlix PIN parental - récupération'
BACKUP_VERSION = 1


# La copie de récupération du PIN est volontairement séparée des favoris et du userdata.
# Elle n'est créée ou mise à jour que si l'utilisateur l'accepte explicitement.
def _backup_code():
	return str(kodi_utils.get_setting(BACKUP_SETTING, '')).strip()


def _set_backup_code(code):
	code = str(code or '').strip()
	kodi_utils.set_setting(BACKUP_SETTING, code)
	try: kodi_utils.clear_property('alkoflix_settings')
	except Exception: pass
	return code


def backup_configured():
	return bool(_backup_code())


def _build_backup_text(pin):
	created = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	return '\n'.join((
		'# alkoFlix parental PIN recovery',
		'# version: %s' % BACKUP_VERSION,
		'# created: %s' % created,
		'# Ce paste privé sert uniquement à récupérer le code PIN parental en cas d’oubli.',
		'',
		'PIN: %s' % str(pin or '').strip(),
		''
	))


def save_pin_backup(pin):
	if not has_user_api_key():
		kodi_utils.logger('alkoPastes parental PIN backup', 'SKIP | not_authorized')
		return {'success': False, 'error': 'not_authorized'}
	pin = str(pin or '').strip()
	if not pin:
		return {'success': False, 'error': 'empty_pin'}
	old_code = _backup_code()
	payload = {'title': BACKUP_TITLE, 'content': _build_backup_text(pin), 'syntax': 'text', 'visibility': 'private', 'expiry': 'NULL'}
	kodi_utils.logger('alkoPastes parental PIN backup save', 'START | cached=%s' % (_mask_code(old_code) or 'empty'))
	created_new = False
	try:
		if old_code:
			result = _request('POST', 'update', payload=payload, params={'id': old_code}, timeout=30.0, log_name='alkoPastes parental PIN backup api')
		else:
			result = _request('POST', 'paste', payload=payload, timeout=30.0, log_name='alkoPastes parental PIN backup api')
			created_new = True
	except Exception as exc:
		if not old_code: raise
		kodi_utils.logger('alkoPastes parental PIN backup update failed', '%s | recreate | %s' % (_mask_code(old_code), exc))
		result = _request('POST', 'paste', payload=payload, timeout=30.0, log_name='alkoPastes parental PIN backup api')
		created_new = True
	new_code = _paste_code(result, old_code)
	if new_code:
		_set_backup_code(new_code)
	kodi_utils.logger('alkoPastes parental PIN backup save', 'RESULT | old=%s | new=%s | created_new=%s' % (_mask_code(old_code), _mask_code(new_code), created_new))
	return {'success': bool(new_code), 'code': new_code, 'created_new': created_new}


def delete_pin_backup():
	code = _backup_code()
	if not code:
		return {'success': True, 'deleted': False}
	if not has_user_api_key():
		kodi_utils.logger('alkoPastes parental PIN backup delete', 'SKIP | not_authorized | cached=%s' % _mask_code(code))
		return {'success': False, 'error': 'not_authorized'}
	try:
		_request('DELETE', 'delete', params={'id': code}, timeout=30.0, log_name='alkoPastes parental PIN backup api')
		_set_backup_code('')
		kodi_utils.logger('alkoPastes parental PIN backup delete', 'OK | %s' % _mask_code(code))
		return {'success': True, 'deleted': True}
	except Exception as exc:
		kodi_utils.logger('alkoPastes parental PIN backup delete failed', '%s | %s' % (_mask_code(code), exc))
		return {'success': False, 'error': str(exc)}
