using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using System.Windows.Forms;
using System.IO;
using System.Configuration;


namespace ABC.KetNoi
{
    class Class_KetNoi
    {
        string str = "";
        String Server = "", User = "", Pass = "", Data = "";
        SqlConnection conn = new SqlConnection();
        public Class_KetNoi()
        {
            string path = Application.StartupPath + "/Data.dat";
            if (System.IO.File.Exists(path))
            {
                using (BinaryReader reader = new BinaryReader(System.IO.File.Open(path, FileMode.Open)))
                {

                    string a = reader.ReadString();
                    // HinhThuc = reader.ReadInt32();
                    string b = reader.ReadString();
                    string c = reader.ReadString();
                    string d = reader.ReadString();
                    // string f = reader.ReadString();
                    //SerVer
                    string[] ar = a.Split(',');
                    byte[] ser = new byte[ar.Length];
                    for (int i = 0; i < ar.Length; i++)
                    {
                        ser[i] = Byte.Parse(ar[i]);
                    }
                    Server = Encoding.ASCII.GetString(ser);
                    //User
                    string[] u = b.Split(',');
                    byte[] use = new byte[u.Length];
                    for (int j = 0; j < u.Length; j++)
                    {
                        use[j] = Byte.Parse(u[j]);
                    }
                    User = Encoding.ASCII.GetString(use);

                    //Pass
                    string[] pa = c.Split(',');
                    byte[] pas = new byte[pa.Length];
                    for (int k = 0; k < pa.Length; k++)
                    {
                        pas[k] = Byte.Parse(pa[k]);
                    }
                    Pass = Encoding.ASCII.GetString(pas);
                    //Data
                    string[] da = d.Split(',');
                    byte[] dat = new byte[da.Length];
                    for (int l = 0; l < da.Length; l++)
                    {
                        dat[l] = Byte.Parse(da[l]);
                    }
                    Data = Encoding.ASCII.GetString(dat);

                }
                str = string.Format("server={0};database={1};uid={2};pwd={3};Connection Timeout=0", Server, Data, User, Pass);

            }
            conn.ConnectionString = str;
            if (conn.State == ConnectionState.Closed)
                conn.Open();

        }


        private string ReadString(byte[] data, ref int index)
        {
            int length = BitConverter.ToInt32(data, index);
            index += 4;
            string result = Encoding.ASCII.GetString(data, index, length);
            index += length;
            return result;
        }

        private string ConvertToString(string input)
        {
            string[] parts = input.Split(',');
            byte[] bytes = new byte[parts.Length];
            for (int i = 0; i < parts.Length; i++)
            {
                bytes[i] = byte.Parse(parts[i]);
            }
            return Encoding.ASCII.GetString(bytes);
        }

        public void SaoLuu(string tGian)
        {

            string key = ConfigurationManager.AppSettings["backup"].ToString();
            T_exc(string.Format("BACKUP DATABASE {0} TO  DISK = '{1}'", Data, Data + "_" + tGian + ".bak"));


        }
        public void XoaDLKetChuyen(int soNgay)
        {
           
            SqlCommand cmd = new SqlCommand("sp_KetChuyen", conn);
            cmd.Parameters.AddWithValue("@Ngay", soNgay);
            cmd.CommandType = CommandType.StoredProcedure;
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

        }
        public DataSet T_opendataset(string strsql)
        {

            string chuoi = str;
            SqlDataAdapter da = new SqlDataAdapter(strsql, conn);
            DataSet ds = new DataSet();
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                da.Fill(ds);
                conn.Close();
                return ds;
            }
            catch
            {
                return null;
            }
        }
        public DataSet getDS(string strsql)
        {

            string chuoi = str;
            SqlCommand cmd = new SqlCommand(strsql, conn);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
        public DataSet T_opendataset_store(string strsql)
        {

            string chuoi = str;
            SqlCommand cmd = new SqlCommand(strsql, conn);
            cmd.CommandTimeout = 999;
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                da.Fill(ds);
                conn.Close();
                return ds;
            }
            catch
            {
                return null;
            }
        }
        public DataSet T_opendataset_store(string strsql,string[]name, object[]value, int para)
        {
            string chuoi = str;          
            SqlCommand command = new SqlCommand(strsql, conn);
            for (int i = 0; i < para; i++)
            {
                command.Parameters.AddWithValue(name[i], value[i]);
            }
            command.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(command);
            DataSet ds = new DataSet();
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                da.Fill(ds);
                conn.Close();
                return ds;
            }
            catch
            {
                return null;
            }
        }
        public int updateTable(string strsql)
        {
            string chuoi = str;
            SqlCommand command = new SqlCommand(strsql, conn);
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                return command.ExecuteNonQuery();
            }
            catch (Exception)
            {

                return 0;
            }
          
        }
        Error_Form _Error_Form;
        string sql_sender;
        public DataSet T_open(string sql)
        {
            sql_sender = sql;
            DataSet dts = T_opendataset(sql);
            if (dts != null)
            {
                return dts;
            }
            else
            {
                _Error_Form = new Error_Form();
                _Error_Form.error_text = sql;
                _Error_Form.FormClosed += new System.Windows.Forms.FormClosedEventHandler(_Error_Form_FormClosed);
                _Error_Form.ShowDialog();
                if (_Error_Form.DialogResult == DialogResult.OK)
                {
                    return T_open(sql);
                }
                else
                {

                    return null;

                }
            }
        }
        public DataSet T_open_store(string sql)
        {
            sql_sender = sql;
            DataSet dts = T_opendataset_store(sql);
            if (dts != null)
            {
                return dts;
            }
            else
            {
                _Error_Form = new Error_Form();
                _Error_Form.error_text = sql;
                _Error_Form.FormClosed += new System.Windows.Forms.FormClosedEventHandler(_Error_Form_FormClosed);
                _Error_Form.ShowDialog();
                if (_Error_Form.DialogResult == DialogResult.OK)
                    return T_opendataset_store(sql);
                else
                    return null;
            }
        }
        void _Error_Form_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
        {
            if (_Error_Form.DialogResult == DialogResult.Cancel)
                System.Environment.Exit(1);
            else
                T_open_store(sql_sender);
        }

        public bool T_executeupdatesqlstr(string strsql)
        {
            string chuoi = str;          
            SqlCommand cmd = new SqlCommand();          
            cmd.CommandText = strsql;
            cmd.CommandType = CommandType.Text;
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
                cmd.Connection = conn;
                cmd.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public void T_exc(string sql)
        {
            sql_sender = sql;
            if (T_executeupdatesqlstr(sql) == true)
            {
                
            }
            else
            {
                _Error_Form = new Error_Form();
                _Error_Form.error_text = sql;
                _Error_Form.FormClosed +=new FormClosedEventHandler(_Error_Form_FormClosed);
                _Error_Form.ShowDialog();
              

            }
        }
    }
}
