using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using Dapper;
using System.Data;
using System.Data.SqlClient;

namespace Bremen_ESG.Controllers
{
    public class BackEndController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private authToken _objToken;

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

            this._objToken = new authToken(this._httpContextAccessor);
        }

        public IActionResult NewsList() {
            if (checkToken() == false)
            {
                return Redirect("~/BackEnd/Index");
            }

            return View();
        }

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

        public IActionResult Logout()
        {
            string token_key = _httpContextAccessor.HttpContext.Request.Cookies["token_key"];

            DbConn dbConn = new DbConn();
            dbConn.sqlConnection().Execute("delete token where token_key = @token_key", new { token_key = token_key });
            dbConn.closeConn();

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

            HttpContext.Response.Redirect("/BackEnd/Index");

            return View();
        }

        public Boolean checkToken()
        {
            this._objToken = new authToken(this._httpContextAccessor);

            if (this._objToken.user_isLogin == false)
            {
                HttpContext.Response.Cookies.Delete("token_key");
                return false;
            }

            @ViewData["User_name"] = this._objToken.user_name;


            return true;
        }
    }
}
