using Dapper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SolarPower.Models;
using SolarPower.Models.LoginViewModel;
using SolarPower.Models.User;
using SolarPower.Repository;
using SolarPower.Repository.Interface;
using SolarPower.Services.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace SolarPower.Controllers
{
    public class LoginController : Controller
    {
        private readonly ILogger<LoginController> logger;
        private readonly IUserRepository userRepository;
        private readonly ISendEmailService sendEmailService;
        public ErrorCode errorCode = new ErrorCode();

        public LoginController(ILogger<LoginController> logger,
                               IUserRepository userRepository,
                               ISendEmailService sendEmailService)
        {
            this.logger = logger;
            this.userRepository = userRepository;
            this.sendEmailService = sendEmailService;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 表單post提交，準備登入
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> IndexAsync(LoginViewModel login)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            User user = null;
            EDFunction edFunction = new EDFunction();
            try
            {
                user = await userRepository.GetOneByAccountAsync(login.Account);

                if (user == null)
                {
                    ViewBag.errMsg = errorCode.GetString("9997"); //帳號或密碼輸入錯誤
                    return View();
                }


                string SHA256Pwd = edFunction.GetSHA256Encryption(login.Password);

                if (string.Compare(user.Password, SHA256Pwd) != 0)
                {
                    ViewBag.errMsg = errorCode.GetString("9997"); //帳號或密碼輸入錯誤
                    return View();
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrMsg = errorCode.GetString("9999");
                string json = System.Text.Json.JsonSerializer.Serialize(login);
                logger.LogError("【Login/Index - 登入資訊】" + json);
                logger.LogError("【Login/Index】" + ex.Message);

                return View();
            }

            HttpContext.Session.SetString("MyAccount", edFunction.AESEncrypt(user.Account)); //將帳號透過AES加密
            HttpContext.Session.SetString("CompanyId", edFunction.AESEncrypt(user.CompanyId.ToString())); //將公司id透過AES加密

            return RedirectToAction("Index", "MapOverview");

        }

        /// <summary>
        /// 登出，Action 記得別加上[Authorize]，不管用戶是否登入，都可以執行SignOut
        /// </summary>
        /// <returns></returns>
        public IActionResult SignOut()
        {
            HttpContext.Session.Clear();

            return RedirectToAction("Index", "Login");//導至登入頁
        }

        /// <summary>
        /// 忘記密碼
        /// </summary>
        /// <returns></returns>
        public IActionResult ForgotPassword()
        {
            return View("~/Views/Login/ForgotPassword.cshtml");
        }

        /// <summary>
        /// 取得新密碼
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ForgotPasswordAsync(ForgotPasswordViewModel forgot)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            var user = await userRepository.GetOneByEmailAsync(forgot.Email);

            if (user == null)
            {
                ViewBag.errMsg = "查無此信箱";
                return View();
            }

            //隨機產生亂數
            Random random = new Random((int)DateTime.Now.Ticks);
            const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
            string random_password = new string(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(chars.Length)]).ToArray());

            EDFunction edFunction = new EDFunction();

            var newPassword = edFunction.GetSHA256Encryption(random_password);

            UpdatePassword update = new UpdatePassword()
            {
                Password = newPassword,
                UpdatedBy = user.Id,
                Id = user.Id
            };

            List<string> properties = new List<string>()
            {
                "Password",
                "UpdatedBy",
                "Id"
            };

            await userRepository.UpdatePassword(update, properties);

            var sendSubject = "變更密碼成功";
            var sendContent = $"您的新密碼為：{random_password}";

            List<string> recipientEmails = new List<string>()
            {
                user.Email
            };

            sendEmailService.Send(recipientEmails, sendSubject, sendContent);

            return RedirectToAction("Index", "Login");
        }
    }
}
