{% extends "templates/web.html" %}

{% block title %} {{_("Reset Password")}} {% endblock %}
{% block head_include %}
{% endblock %}
{% block page_content %}
<section class="for-reset-password d-block">
	<div class="page-card-head">
		<h4 class="reset-password-heading">{{ _("Reset Password") if frappe.db.get_default('company') else _("Set Password")}}</h4>
	</div>
	<div class="page-card">
		<form id="reset-password">
			<div class="form-group">
				<input id="old_password" type="password"
					class="form-control mb-4" placeholder="{{ _('Old Password') }}" autocomplete="current-password">
			</div>
			<div class="form-group">
				<input id="new_password" type="password"
					class="form-control mb-4" placeholder="{{ _('New Password') }}" autocomplete="new-password">
				<span class="password-strength-indicator indicator"></span>
			</div>
			<div class="form-group">
				<input id="confirm_password" type="password"
					class="form-control" placeholder="{{ _('Confirm Password') }}" autocomplete="new-password">

			</div>
			<p class="password-mismatch-message text-muted small hidden mt-2"></p>
			<p class='password-strength-message text-muted small mt-2 hidden'></p>
			<button type="submit" id="update" disabled = true style="cursor: not-allowed;"
				class="btn btn-primary btn-block btn-update">{{_("Confirm")}}</button>
		</form>
		{%- if not disable_signup -%}
			<div class="text-center sign-up-message">
				{{ _("Don't have an account?") }}
				<a href="/login#signup">{{ _("Sign up") }}</a>
			</div>
		{%- endif -%}
	</div>
</section>
<style>
	.page-card-head {
		padding: max(5vh, 30px) 0 14px 0px;
		margin: 0 auto;
		text-align: center;
		font-size: var(--text-xl);
		font-weight: 600;

	}
	.page-card-head img {
		max-height: 42px;
	}

	.page-card-head h4 {
		margin-top: 1rem;
		font-size: var(--text-xl);
		font-weight: var(--weight-semibold);
		letter-spacing: 0.01em;
		color: var(--text-color);
	}
</style>

<script>

frappe.ready(function() {
	// URL args
	const key = frappe.utils.get_url_arg('key');
	const password_expired = frappe.utils.get_url_arg('password_expired');
	// inputs, paragraphs and button elements
	const old_password = $('#old_password');
	const new_password = $('#new_password');
	const confirm_password = $('#confirm_password');
	const update_button = $('#update');
	const password_strength_indicator = $('.password-strength-indicator');
	const password_strength_message =$('.password-strength-message');
	const password_mismatch_message = $('.password-mismatch-message');
	// Info text
	const password_not_same_as_old_password = "{{ _('New password cannot be same as old password') }}";
	const password_mismatch = "{{ _('Passwords do not match') }}";
	const password_strength_message_success = "{{ _('Success! You are good to go 👍') }}";

	if(key) {
		old_password.parent().toggle();
	}

	if(password_expired) {
		$(".password-box").html("{{ _('The password of your account has expired.') }}");
	}

	$("#reset-password").on("submit", function() {
		return false;
	});

	new_password.on("keypress", function(e) {
		if(e.which===13) update_button.click();
	})

	update_button.click(function() {
		var args = {
			key: key || "",
			old_password: old_password.val(),
			new_password: new_password.val(),
			confirm_password: confirm_password.val(),
			logout_all_sessions: 1
		}
		if (!args.old_password && !args.key) {
			frappe.msgprint({
				title: "{{ _('Missing Value') }}",
				message: "{{ _('Please enter your old password.') }}",
				clear: true
			});
		}
		if (!args.new_password) {
			frappe.msgprint({
				title: "{{ _('Missing Value') }}",
				message: "{{ _('Please enter your new password.') }}",
				clear: true
			});
		}
		if (args.old_password === args.new_password) {
			frappe.msgprint({
				title: "{{ _('Invalid Password') }}",
				message: password_not_same_as_old_password,
			});
			password_strength_message.addClass('hidden');
			return;
		}

		if (args.new_password !== args.confirm_password) {
			password_mismatch_message.text(password_mismatch)
				.removeClass('hidden text-muted').addClass('text-danger');
			password_strength_message.addClass('hidden');
			return;
		}

		frappe.call({
			type: "POST",
			method: "frappe.core.doctype.user.user.update_password",
			btn: update_button,
			args: args,
			statusCode: {
				401: function() {
					$(".page-card-head .reset-password-heading").text("{{ _('Invalid Password') }}");
					frappe.msgprint({
						title: "{{ _('Invalid Password') }}",
						message: "{{ _('Your old password is incorrect.') }}",
						// clear any server message
						clear: true
					});
				},
				410: function({ responseJSON }) {
					const title = "{{ _('Invalid Link') }}";
					const message = responseJSON.message;
					$(".page-card-head .reset-password-heading").text(title);
					frappe.msgprint({ title: title, message: message, clear: true });
				},
				200: function(r) {
					$("input").val("");
					strength_indicator.addClass("hidden");
					strength_message.addClass("hidden");
					$(".page-card-head .reset-password-heading")
						.html("{{ _('Status Updated') }}");
					frappe.msgprint({
						title: "{{ _('Password set') }}",
						message: "{{ _('Your new password has been set successfully.') }}",
						clear: true
					});
					// ASM UI: React login; manual_login=1 forces logout so user signs in manually (update_password auto-logs in).
					setTimeout(function() {
						window.location.href = "{{ frappe.utils.get_url('/asm_app/login?manual_login=1') }}";
					}, 2000);
				}
			}
		});

		return false;
	});

	window.strength_indicator = password_strength_indicator;
	window.strength_message = password_strength_message;

	new_password.on('keyup', function() {
		window.clear_timeout();
		window.timout_password_strength = setTimeout(window.test_password_strength, 200);
	});

	$("#old_password, #new_password, #confirm_password").on("keyup paste", frappe.utils.debounce(function () {
		let common_conditions = new_password.val() && confirm_password.val() && new_password.val() === confirm_password.val()

		if (new_password.val() && old_password.val() === new_password.val()) {
			password_mismatch_message.text(password_not_same_as_old_password)
				.removeClass("hidden text-muted").addClass("text-danger");

			password_strength_message.addClass("hidden");
		}
		if ((new_password.val() || old_password.val) && old_password.val() !== new_password.val()) {
			password_mismatch_message.addClass("hidden");
			password_strength_message.removeClass("hidden");
			password_mismatch_message.text('')
		}

		if (new_password.val() === confirm_password.val() && old_password.val() !== new_password.val() ) {
			password_mismatch_message.addClass("hidden");
			password_strength_message.removeClass("hidden");
		}
		if (confirm_password.val() &&  new_password.val() !== confirm_password.val()) {
			password_mismatch_message.text(password_mismatch)
				.removeClass("hidden text-muted").addClass("text-danger");
			password_strength_message.addClass("hidden");
		}
		if ((key || (!key && old_password.val() )) && common_conditions ) {
			update_button.prop("disabled", false).css("cursor", "pointer");
		}
		else {
			update_button.prop("disabled", true).css("cursor", "not-allowed");
		}
		},500)
	)

	window.test_password_strength = function() {
		window.timout_password_strength = null;

		var args = {
			key: key || "",
			old_password: old_password.val(),
			new_password: new_password.val()
		}

		if (!args.new_password) {
			set_strength_indicator('grey', {'warning': "{{ _('Please enter the password') }}" });
			return;
		}

		return frappe.call({
			method: 'frappe.core.doctype.user.user.test_password_strength',
			args: args,
			callback: function(r) {
				console.log(r.message);
			},
			statusCode: {
				401: function() {
					$('.page-card-head .reset-password-heading')
						.text("{{ _('Invalid Password') }}");
				},
				200: function(r) {
					if (r.message) {
						var score = r.message.score,
							feedback = r.message.feedback;

						if (!feedback) {
							return;
						}

						feedback.score = score;

						if (feedback.password_policy_validation_passed) {
							set_strength_indicator('green', feedback);
						}else{
							set_strength_indicator('red', feedback);
						}
					}
				}
			}

		});
	};

	window.set_strength_indicator = function(color, feedback) {
		var message = [];
		feedback.help_msg = "";
		if(!feedback.password_policy_validation_passed){
			feedback.help_msg = "<br>" + "{{ _('Hint: Include symbols, numbers and capital letters in the password') }}";
		}
		if (feedback) {
			if(!feedback.password_policy_validation_passed){
				if (feedback.suggestions && feedback.suggestions.length) {
					message = message.concat(feedback.suggestions);
				} else if (feedback.warning) {
					message.push(feedback.warning);
				}
				message.push(feedback.help_msg);

			} else {
				message.push(password_strength_message_success);
			}
		}
		password_mismatch_message.addClass('hidden');

		strength_message.html(message.join(' ') || '').removeClass('hidden');
	}

	window.clear_timeout = function() {
		if (window.timout_password_strength) {
			clearTimeout(window.timout_password_strength);
			window.timout_password_strength = null;
		}
	};
});

</script>

{% endblock %}

{% block style %}
<style>
	body {
		background-color: var(--bg-color);
	}

	.navbar-brand, .navbar-toggler,
	#website-post-login, .logged-in, .btn-login-area, .nav-avatar,
	footer.web-footer, .web-footer, .footer-logo-extension, .footer-powered {
		display: none !important;
	}

	.password-strength-indicator {
		float: right;
		padding: 15px;
		margin-top: -38px;
		margin-right: -7px;
	}

	.password-strength-message {
		margin-top: -10px;
	}
	{% include "templates/styles/card_style.css" %}
</style>
{% endblock %}
