using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Cors;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using static DbTableClass;
using static resultClass;
using Dapper.Contrib.Extensions;
using System.Reflection.Metadata.Ecma335;
using Microsoft.Extensions.Options;

public class authToken
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public string user_uid { get; set; }
    public string user_id { get; set; }
    public string user_name { get; set; }
    public string user_perm { get; set; }
    public Boolean user_isLogin { get; set; }
    public string error_msg { get; set; }
    public HttpRequest myRequest { get; set; }

    public authToken(IHttpContextAccessor httpContextAccessor)
    {
        this._httpContextAccessor = httpContextAccessor;

        SqlConnection conn = new SqlConnection(GlobalClass.appsettings("ConnectionStrings:SQLConnectionString"));
        DbConn dbConn = new DbConn();
        dbConn.sqlConnection().Execute("delete token where token_expireddate < @now", new { now = DateTime.Now });
        dbConn.closeConn();

        try
        {
            if (_httpContextAccessor.HttpContext.Request.Cookies["token_key"] == null)
            {
                user_isLogin = false;
                error_msg = "no this cookie";
                return;
            }



            string token_key = _httpContextAccessor.HttpContext.Request.Cookies["token_key"];

            var tokenData = dbConn.sqlConnection().Query("select * from token where token_key = @token_key", new { token_key = token_key });

            //CookieOptions cookieOptions = new CookieOptions();

            //cookieOptions.Secure = true;
            //cookieOptions.Expires = DateTime.Now.AddMinutes(intexpireMin);

            if (tokenData.Count() == 0)
            {

                _httpContextAccessor.HttpContext.Response.Cookies.Delete("token_key");

                user_isLogin = false;
                error_msg = "not this account";
                dbConn.closeConn();
                return;
            }

            var tokenItem = tokenData.ElementAt(0);


            if (tokenItem.user_uid == GlobalClass.appsettings("Admin:uid") && tokenItem.user_id == GlobalClass.appsettings("Admin:id"))
            {
                user_uid = tokenItem.user_uid;
                user_id = tokenItem.user_id;
                user_name = "系統管理員";
                user_perm = GlobalClass.appsettings("Admin:perm");
                user_isLogin = true;

                int intMin = 240;

                if (tokenItem.token_isremember == "Y")
                {
                    intMin = 60 * 24 * 14;
                }

                dbConn.sqlConnection().Execute("update token set token_expireddate = @token_expireddate " +
                "where token_key = @token_key", new { token_expireddate = DateTime.Now.AddMinutes(intMin), token_key = token_key });

                dbConn.closeConn();

                CookieOptions options = new CookieOptions()
                {
                    Secure = true,
                    Expires = DateTime.Now.AddMinutes(intMin)
                };

                //_httpContextAccessor.HttpContext.Response.Cookies.Delete("web_token_key");
                _httpContextAccessor.HttpContext.Response.Cookies.Append("token_key", token_key, options);

                return;
            }
            else {

                user loginUser = conn.QueryFirstOrDefault<user>("select * from users where user_uid = @user_uid and user_id = @user_id", new { user_uid = tokenItem.user_uid , user_id = tokenItem.user_id });
                 
                if (loginUser == null)
                {
                    dbConn.sqlConnection().Execute("delete token where token_key = @token_key", new { token_key = token_key });

                    user_isLogin = false;
                    error_msg = "找不到此token用戶資料";
                    dbConn.closeConn();
                    return;
                }

                if (loginUser.user_onjob == "N") {
                    dbConn.sqlConnection().Execute("delete token where token_key = @token_key", new { token_key = token_key });

                    user_isLogin = false;
                    error_msg = "此token用戶已經離職";
                    dbConn.closeConn();
                    return;
                }

                user_uid = tokenItem.user_uid;
                user_id = tokenItem.user_id;
                user_name = loginUser.user_name;
                user_perm = loginUser.user_perm;
                user_isLogin = true;

                int intMin = 20;

                if (tokenItem.token_isremember == "Y")
                {
                    intMin = 60 * 24 * 7;
                }

                dbConn.sqlConnection().Execute("update token set token_expireddate = @token_expireddate " +
                "where token_key = @token_key", new { token_expireddate = DateTime.Now.AddMinutes(intMin), token_key = token_key });


                CookieOptions options = new CookieOptions()
                {
                    Secure = true,
                    Expires = DateTime.Now.AddMinutes(intMin)
                };

                //_httpContextAccessor.HttpContext.Response.Cookies.Delete("web_token_key");
                _httpContextAccessor.HttpContext.Response.Cookies.Append("token_key", token_key, options);

                dbConn.closeConn();

            }
        }
        catch (Exception ex)
        {
            conn.Close(); 
            dbConn.closeConn();
            user_isLogin = false;
            error_msg = ex.Message;
        }
    }
}
