using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Data;
namespace CitySunlight
{
    public static class UserManager
    {
        private const String tbname = "tb_user";
        private static Dictionary<String, int> trytimes = new Dictionary<string, int>();
        private static SqlHelper sql = new SqlHelper("Data Source=.;Initial Catalog=myApplication;User ID=sa;Password=325325");

        public static int ErrLogin(String username)
        {
            return UpdateTimes(username, true);
        }

        public static int GetTimes(String username)
        {
            return UpdateTimes(username, false);
        }

        private static int UpdateTimes(String username, bool add)
        {
            if (!trytimes.ContainsKey(username))
            {
                trytimes.Add(username, add ? 1 : 0);
            }
            else
            {
                if (add) { trytimes[username] += 1; };
            }
            return trytimes[username];
        }

        public static bool LoginUser(String username, String password)
        {
            DataTable dt = sql.ExecuteDataTable("select * from " + tbname + " where UserName='" + username + "' and PassWord='" + password + "'", CommandType.Text);
            //return "select * from user where username='" + username + "' and password='" + password + "'";
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            UpdateTimes(username, true);
            return false;
        }

        public static bool isExist(String username)
        {
            DataTable dt = sql.ExecuteDataTable("select * from " + tbname + " where UserName='" + username + "'", CommandType.Text);
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            return false;
        }

        public static bool RegisterUser(String username, String password)
        {
            int insert = sql.ExecuteNonQuery("insert into " + tbname + "(UserName,PassWord) values('" + username + "','" + password + "')");
            if (insert > 0)
            {
                return true;
            }
            return false;
        }
    }
}