using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
using Utils;

public partial class register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user_id"] != null)
        {
            Response.Redirect("/index.aspx");
            return;
        }
    }

    protected void onRegisterClick(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Entities entities = new Entities();
            User user = new User();
            user.username = username_box.Text.Trim();
            user.salt = PasswordHash.getNextSalt();
            user.password = PasswordHash.Hash(password_box.Text, user.salt);
            entities.Users.Add(user);
            try
            {
                entities.SaveChanges();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                foreach(var errors in ex.EntityValidationErrors)
                {
                        error_message.Text += errors.ValidationErrors.First().ErrorMessage;
                }
                return;
            }
            Response.Redirect("/login.aspx");
        }
    }

    protected void validateUsername(object sender, ServerValidateEventArgs e)
    {
        Entities entities = new Entities();
        if ((from u in entities.Users where u.username == username_box.Text.Trim() select u.username).SingleOrDefault() != null)
        {
            e.IsValid = false;
            username_validator.Text = "El nombre de usuario ya esta en uso";
            return;
        }

        e.IsValid = true;
    }

    protected void validatePassword(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = true;
    }
}