using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using PositioningWebApp.Models.DB;
using PositioningWebApp.Services.Validation;
using PositioningWebApp.Models.UserProfile;
using PositioningWebApp.Security;
using Microsoft.EntityFrameworkCore;
using PositioningWebApp.DBServices;

namespace PositioningWebApp.Pages.Home.Profile
{
    public class ProfileModel : PageModel
    {
		
		private DevicesOnMapBackgroundContext databaseManager;
		[BindProperty]
		public UserProfile Profile { get; set; }
		public ProfileModel (DevicesOnMapBackgroundContext context)
		{
			try
			{
				databaseManager = context;
			}
			catch (Exception ex)
			{
				throw ex;
			}
		}


		public void OnGet()
        {
			Profile = new UserService().GetUser(Convert.ToInt32(Convert.ToInt32(User.Claims.ToList()[3].Value)), databaseManager);
		}

		public IActionResult OnPostSave()
		{
			try
			{
				bool saveWithPassword = false;
				if (!new Email().Validate(Profile.Email))
				{
					ModelState.AddModelError(string.Empty, "Value already exists.");
					return Page();
				}
				if (Profile.Password != null && Profile.Password2 != null)
				{
					if (Profile.Password.Length < 7 && !Profile.Password.Equals(Profile.Password2))
					{
						// Setting.  
						ModelState.AddModelError(string.Empty, "Password has to be longer than 7 characters or password are not equal");
						return this.Page();
					}
					else
					{
						saveWithPassword = true;
					}
				}
				new UserService().UpadateUser(saveWithPassword, Profile.ID, Profile.FirstName,
					Profile.Surname, Profile.Email, Profile.Password, Profile.Phone, databaseManager);

				return Page();

			}
			catch (Exception ex)
			{
				throw ex;
			}
		}
	}
}