using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Spaces;
using System.IO;
using System.Collections.Generic;
public partial class reg_step1 : System.Web.UI.Page
{
    bool isCreateDir = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        
        if (!IsPostBack)
        {
            BindPage();
        }
    }

    private void BindPage()
    {
        dropYear.Items.Clear();
        for (int y = 1930; y < 2007; y++)
        {
            dropYear.Items.Add(new ListItem(y.ToString(),y.ToString()));
        }
        dropYear.SelectedValue = "1986";
        dropMonth.Items.Clear();
        for (int m = 1; m < 13; m++)
        {
            dropMonth.Items.Add(new ListItem(m.ToString(),m.ToString()));
        }
        DropDay.Items.Clear();
        for (int d = 1; d < 32; d++)
        {
            DropDay.Items.Add(new ListItem(d.ToString(),d.ToString()));
        }
        //chkAdv.Text = Globals.Text["Register_HighLevel"];
        btnReg.Text = Globals.Text["Register_OpenSpace"];
        ListItem lif = new ListItem(Globals.Text["Register_SexF"], "1");
       
        ListItem lim = new ListItem(Globals.Text["Register_SexM"], "2");
        Gender.Items.Add(lif);
        Gender.Items.Add(lim);
        string iptDomain = "<input type='text' name='mydomain' id='mydomain' class=\"myinput\" onfocus=\"this.className='myinputfocus'\" onblur=\"this.className='myinput'\" style=\"width:80px\"/>";
        txtUserDomain.Text = string.Format(Config.GetConfig().DefaultDomain,iptDomain);
    }
    protected void btnReg_Click(object sender, EventArgs e)
    {
        string username = txtUsername.Text.Trim().ToLower();
        string account =Request.Form["mydomain"]; 
        string password = txtPassword.Text;
        string email = txtEmail.Text;
        string nickName = txtNickName.Text;
        string ipAddress = Request.UserHostAddress;
        Spaces.Gender g;
        int siteDayIPLimit = Globals.GetSiteSettings().DayRegIPCount;
        if (siteDayIPLimit > 0)
        {
            int count = SpacesDataProvider.Instance().GetDayRegIPCount(ipAddress);
            if (count > siteDayIPLimit)
            {
                Message.Text = "<script>_error_msg_show('IP超出许可限制，请24小时后再注册:S');</script>";
                return;
            }
        }
       
        if (Gender.SelectedIndex == -1)
        {
            g = Spaces.Gender.None;
        }
        else
        {
            g = (Spaces.Gender)int.Parse(Gender.SelectedValue);
        }
      
       

        User user = new User();
        user.Username = username;
        user.Account = account;
        user.Password = Utils.PasswordFormat(password);
        user.Email = email;
        user.NickName = nickName;
        user.Gender = g;
        user.Address = txtAddress.Text;

        user.Question = string.Empty;
        user.Answer = string.Empty;
        user.IdNumber = string.Empty;
        user.City = Request.Form["city"];

        user.RegIP = Request.UserHostAddress;
        string url = string.Format("{0}{1}/{2}", SpacesContext.Current.Domain, Globals.ApplicationPath,Globals.GetSiteUrls().Account(account));
        user.UrlAddress = string.Format("http://{0}",Utils.Replace(url,"//","/"));
      
            try
            {
                user.Birthday = new DateTime(Convert.ToInt32(dropYear.SelectedValue), Convert.ToInt32(dropMonth.SelectedValue), Convert.ToInt32(DropDay.SelectedValue));
            }
            catch {
                user.Birthday = new DateTime(1900,1,1);
            }
         
    

        
        CreateUserStatus status= Users.CreateUser(user);
        if (status != CreateUserStatus.Created)
        {
            Message.Text = GetCreateUserErrMsg(status);
            return;
        }
            SetTicket(user.Account, true);
            Directorys.InitUserDirectorys(user.Account);//初始化用户目录

        if(isCreateDir)
            CreateUserDir(user.Account);

        //更新用户配置文件
           
            UserConfig uc = user.Config;
            uc.Language = Config.GetConfig().DefaultLanguage;//设置默认语言
             ThemeHelp.SetDefaultTheme(uc);//设置默认皮肤
            Users.UpdateUserConfig(uc);
            CreateDefaultPost(uc.BlogID);//创建默认主题
     Response.Redirect("reg_step2.aspx?user=" +HttpUtility.UrlEncode(user.Username));

    }
    void CreateUserDir(string account)
    {
        string path =Path.Combine( Server.MapPath(Globals.ApplicationPath),account);
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        string fileName = Path.Combine(path,"Default.aspx");
        File.Create(fileName);

    }
    /// <summary>
    /// 创建默认主题
    /// </summary>
    /// <param name="blogID">博客ID</param>
    private void CreateDefaultPost(int blogID)
    {
        DayBook post = new DayBook();
        post.BlogID = blogID;
        post.DateAdded = post.DateUpdated = DateTime.Now;
        post.Author = "系统";
        post.EnableComment = true;
        post.FeedBackCount = 0;
        post.PostType = PostType.BlogPost;
        post.Price = 0;
        post.SourceName = Request.UserHostAddress;
        post.Tags = new List<string>();
        post.TitleUrl = "http://xiaoxiao.bfor.cn";
        //post.ViewCount = 0;
        post.Title = "嗨！亲爱的朋友们，欢迎您光临我的空间";
        post.Text = @"我已经在这儿安家了，欢迎你时常过来做客，大家多多交流哦。我会把一些新鲜有趣的东西记录下来一块与你分享。也希望你记住我的BLOG地址，你可以把她添加到你的收藏夹，也可以把她复制下来告诉你的朋友们。 <BR>
        <BR>
        　　 ：）<BR>
        <BR>";
        Blogs.CreatePost(post);
    }
    private string GetCreateUserErrMsg(CreateUserStatus status)
    {
        string msg = "未知错误！";
        switch (status)
        { 
            case CreateUserStatus.DisallowedUsername:
                msg = "该帐号禁止注册！";
                break;
            case CreateUserStatus.DuplicateEmailAddress:
                msg = "Email地址已存在！";
                break;
            case CreateUserStatus.DuplicateUsername:
                msg = "用户名已存在！";
                break;
            case CreateUserStatus.DuplicateAccount:
                msg = "帐号(网址部分)已存在！";
                break;
            case CreateUserStatus.InvalidEmail:
                msg = "无效的Email地址";
                break;
            case CreateUserStatus.InvalidUserName:
                msg = "无效的帐号名！";
                break;
            
        }
        return Msg.GetErrMsg(msg);
    }

    public void SetTicket(string name, bool isPersistent)
    {
        FormsAuthentication.SetAuthCookie(name, isPersistent);


        string userData = "username|userid|userdepart";

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1,
        name,
        System.DateTime.Now,
        System.DateTime.Now.AddDays(7),
        isPersistent,
        userData,
        FormsAuthentication.FormsCookiePath);

        // Encrypt the ticket. 
        string encTicket = FormsAuthentication.Encrypt(ticket);

        // Create the cookie. 
        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

        // FormsAuthentication.RedirectFromLoginPage(name, isPersistent);
    }
    bool CheckUsername(string name)
    {
        for (int i = 0; i < name.Length; i++)
        {
            int ncode = (int)name[i];
            if (name[i] != ' ' && (ncode < 19968 || ncode > 40870) && (ncode < 48 || ncode > 57) && (ncode < 64 || ncode > 90) && (ncode < 97 || ncode > 122) && ncode != 46)
            {
                return false;
            }
        }
        return true;
    }
}
