using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using JuSNS.Model;
using JuSNS.Home;
using JuSNS.Config;
using JuSNS.Common;

namespace JuSNS.Web
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }


        protected void Application_End(object sender, EventArgs e)
        {

        }
        protected void Application_Error(object sender, EventArgs e)
        {
            string rooDir = string.Empty;
            string  TMPDir = JuSNS.Config.UiConfig.RootDir;            
            Exception x = Server.GetLastError().GetBaseException();
            JuSNS.UI.WebHint.ShowError(rooDir, x.Message, Request.UrlReferrer.ToString(), false);
        }

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            OnlineUserInfo info = new OnlineUserInfo();
            OnlineUser user = new OnlineUser();
            HttpCookie SNSToKenCookie = Context.Request.Cookies["SNSUserPassPort"];

            bool islogin = true;
            if (SNSToKenCookie == null || SNSToKenCookie["token"] == null || SNSToKenCookie["token"] == "")
            {
                islogin = false;
            }
            if (islogin)
            {
                string userCookie = SNSToKenCookie["token"];
                string UserPortrait = SNSToKenCookie["headpic"];
                string UserName = Input.URLDecode(SNSToKenCookie["username"]);
                string desstr = JuSNS.Common.DES.Decrypt(userCookie, SecretConfig.UserKey, SecretConfig.UserIV);
                string[] userInfo = desstr.Split(SecretConfig.UserSeparator);
                info.LastIP = Request.UserHostAddress;
                info.LastTime = DateTime.Now;
                int userid = 0;
                int.TryParse(userInfo[0], out userid);
                info.UserID = userid;
                info.UserName = userid == 0 ? "ÓÎ¿Í" : UserName;
                info.LastURL = Request.Url.ToString();
            }
            else
            {
                info.LastIP = Request.UserHostAddress;
                info.LastTime = DateTime.Now;
                info.UserID = 0;
                info.UserName = "ÓÎ¿Í";
                info.LastURL = Request.Url.ToString();
            }

            if (user.CheckOnline(info.UserID, info.LastIP))
            {
                user.Update(info);
            }
            else
            {
                user.Add(info);
            }
            user.DeleteExpires();
        }
    }
}