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 Microsoft.Data.SqlClient;
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;

        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 });

            if (tokenData.Count() == 0) {
                user_isLogin = false;
                error_msg = "not this account";
                dbConn.closeConn();
                return;
            }

            var tokenItem = tokenData.ElementAt(0);


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

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

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