using System;
using System.Web;
using System.Web.UI;
using System.Collections.Generic;
using System.Text;
using JuSNS.Model;
using JuSNS.Common;
using JuSNS.Config;
using JuSNS.Home;

namespace JuSNS.UI.Page
{
    public class UserPage : BasePage
    {
        /// <summary>
        /// 默认登录地址
        /// </summary>
        private static string loginUrl = "/";
        private bool _UserCertificate = true;
        protected int VisitedUserID = 0;
        protected EnumPrivacyType Enum_Privacy_Type;
        protected override void Logout()
        {
            base.Logout();
            Context.Response.End();
        }
        public UserPage()
        {
            this.Load += new EventHandler(UserPage_Load);
        }

        /// <summary>
        /// LOAD事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserPage_Load(object sender, EventArgs e)
        {
            CheckLogin();
            //隐私检查
            if (this.VisitedUserID != 0)
            {
                if (!PrivacyAvailable(this.Enum_Privacy_Type, this.UserID, this.VisitedUserID))
                {
                    this.PageError("当前用户隐私设置不允许您查看", Request.RawUrl);
                }
            }
        }

        /// <summary>
        /// 检查登录状态
        /// </summary>
        protected override void CheckLogin()
        {
            SNSToKenCookie = Context.Request.Cookies["SNSUserPassPort"];
            if (SNSToKenCookie == null || SNSToKenCookie["token"] == null || SNSToKenCookie["token"]==string.Empty)
            {
                base.CheckResultShow(EnumLoginState.Err_TimeOut, loginUrl);
            }
            string userCookie = SNSToKenCookie["token"];
            this.UserPortrait = SNSToKenCookie["headpic"];
            this.UserName = Input.URLDecode(SNSToKenCookie["username"]);
            string desstr = DES.Decrypt(userCookie, SecretConfig.UserKey, SecretConfig.UserIV);
            string[] userInfo = desstr.Split(SecretConfig.UserSeparator);
            EnumLoginState state = EnumLoginState.Err_TimeOut;
            int loginTimes = 0;
            if (userInfo.Length == 3)
            {
                UserID = int.Parse(userInfo[0]);
                string pass = userInfo[1];
                string cookip = userInfo[2];
                if (cookip != Public.GetClientIP())
                {
                    state = EnumLoginState.Err_TimeOut;
                }
                else
                {
                    User us = new User();
                    state = us.CheckLogin(UserID, pass, out loginTimes);
                    string rURL = Request.Url.ToString().ToLower();
                    if (rURL.IndexOf("/home/space/edit.aspx") == -1 && rURL.IndexOf("/home/space/edit-link.aspx") == -1 && rURL.IndexOf("/home/space/userheadphoto.aspx") == -1 && rURL.IndexOf("/home/space/userheadphoto1.aspx") == -1)
                    {
                        if (loginTimes < 2 && string.IsNullOrEmpty(this.GetHeadPath(UserID)))
                        {
                            Response.Redirect(rooDir + "/home/space/edit.aspx?f=1");
                        }
                    }
                }
            }
            if (!(state == EnumLoginState.Succeed))
            {
                CheckResultShow(state, rooDir + "/home");
            }
        }

        /// <summary>
        /// 设置是否需要验证，要在子类的构造函数里设置
        /// </summary>
        protected bool UserCertificate
        {
            set { _UserCertificate = value; }
        }

        /// <summary>
        /// 设置登录的Cookie
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="userName">用户姓名</param>
        /// <param name="Password">已Md5加密后的密码</param>
        /// <param name="userPortrait">用户的头像</param>
        /// <param name="isAlways">是否保持登录状态(下次同一计算机免登录)</param>
        static public void SetCookie(int userId, string userName, string Password, string userPortrait, bool isAlways)
        {
            HttpCookie SNSToKenCookie = new HttpCookie("SNSUserPassPort");

            string s = userId.ToString() + SecretConfig.UserSeparator.ToString() + Password + SecretConfig.UserSeparator.ToString() + Public.GetClientIP();
            SNSToKenCookie["token"] = DES.Encrypt(s, SecretConfig.UserKey, SecretConfig.UserIV);
            SNSToKenCookie["headpic"] = userPortrait;
            SNSToKenCookie["username"] = Input.URLEncode(userName);
            SNSToKenCookie.Domain = UiConfig.CookieDomain;
            SNSToKenCookie.Secure = false;
            if (isAlways)
            {
                SNSToKenCookie.Expires = DateTime.Now.AddYears(1);
            }
            HttpContext.Current.Response.AppendCookie(SNSToKenCookie);
        }
    }
}
