using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;




using System.IO;
using ABC.KetNoi;
using ABC.File;

namespace ABC
{
    public partial class T_Update : Form
    {
        public T_Update()
        {
            InitializeComponent();
        }

        private void T_Share_Load(object sender, EventArgs e)
        {
            get_database();
            progess_in();
            GETFOLDER();
            //  string name = System.Environment.MachineName;
            //  txtthumuc.Text = "Data_" + T_Remember_sys.Ngay_DN.Day.ToString() + "_" + T_Remember_sys.Ngay_DN.Month.ToString() + "_" + T_Remember_sys.Ngay_DN.Year.ToString() +"_"+ DateTime.Now.Hour.ToString() + "h" + DateTime.Now.Minute.ToString()+"("+name+")";
        }
        T_Connect_master mt = new T_Connect_master();
        DataTable dt_main;
        public void get_database()
        {
            #region
            string sql = "SELECT DB_NAME(database_id) AS DatabaseName,Name AS Logical_Name,Physical_Name, (size*8)/1024 SizeMB FROM sys.master_files WHERE DB_NAME(database_id) = 'ABC'";
            dt_main = mt.T_open(sql).Tables[0];

            #endregion
        }
        string path_dau;
        public void progess_in()
        {
            Class_KetNoi db = new Class_KetNoi();
            int thamso = 1;
            string[] arr_name = new string[thamso];
            object[] arr_value = new object[thamso];
            arr_name[0] = "@ID";
            arr_value[0] = Get_CauHinh.Dt_Login.Rows[0]["ID"].ToString().ToUpper();
            DataTable dt = db.T_opendataset_store("sp_CauHinh_TheoID", arr_name, arr_value, thamso).Tables[0];
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                txtduongdan.Text = row["ThuMucPhucHoi"].ToString();
                path_dau= row["ThuMucPhucHoi"].ToString();
            }
            GETFOLDER();
        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        FolderBrowserDialog f = new FolderBrowserDialog();
        private void simpleButton3_Click(object sender, EventArgs e)
        {

        }
        public DataTable dt;
        public void GETFOLDER()
        {
            if (txtduongdan.Text != "to" && txtduongdan.Text != "")
            {
                string[] files = Directory.GetFiles(txtduongdan.Text);
                string[] subdirectories = Directory.GetDirectories(txtduongdan.Text);

                long size = files.Sum(x => new FileInfo(x).Length);
                dt = new DataTable();
                dt.Columns.Add("NAME");
                dt.Columns.Add("SIZE");
                dt.Columns.Add("PA");
                dt.Columns.Add("LAST");
                foreach (string s in subdirectories)
                {
                    size = GetDirectorySize(s);
                    DirectoryInfo fi1 = new DirectoryInfo(s);
                    // DateTime created = fi1.LastWriteTime;
                    DataRow dtr = dt.NewRow();
                    dtr["NAME"] = fi1.Name;
                    long filesize = size / (1024 * 1024);
                    dtr["SIZE"] = filesize;
                    dtr["PA"] = fi1.FullName;
                    dtr["LAST"] = fi1.LastWriteTime;
                    dt.Rows.Add(dtr);
                }
            }
            gc5.DataSource = dt;
        }
        public static long GetDirectorySize(string path)
        {
            string[] files = Directory.GetFiles(path);
            string[] subdirectories = Directory.GetDirectories(path);

            long size = files.Sum(x => new FileInfo(x).Length);
            foreach (string s in subdirectories)
                size += GetDirectorySize(s);

            return size;
        }

        string PATHCHON;
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            PATHCHON = gv5.GetRowCellDisplayText(gv5.FocusedRowHandle, "PA");
            if (PATHCHON == null)
            {
                msgbox.dialog_OK_error("Vui lòng chọn thư mục.");
            }
            else
            {

                DialogResult dia = msgbox.dialog_yes_no("Cập nhật dữ liệu từ thư mục \n " + PATHCHON + " .\n Bạn có muốn tiếp tục không ?");
                if (dia == DialogResult.Yes)
                {
                    ok();

                }
                else
                {
                }
            }


        }
        public void ok()
        {
            if (check_thumuc_file() == true)
            {
                get_file_sql();
                check_va_taothumuc_local();

                detach();
                copy_thumucxoa();
                prelace_datacu();
                attach();
                msgbox.dialog_OK_info("Thành Công");
                this.DialogResult = DialogResult.OK;
                this.Close();

            }
        }
        string sql_file = "";
        public void get_file_sql()
        {
            if (dt_main.Rows.Count > 0)
            {
                sql_file = dt_main.Rows[0]["Physical_Name"].ToString();
                sql_file = System.IO.Path.GetDirectoryName(sql_file); folder_root = sql_file;

            }
        }
        public bool check_thumuc_file()
        {

            string path3 = PATHCHON + @"\ABC_Data.mdf";
            string path4 = PATHCHON + @"\ABC_Log.ldf";

            if (System.IO.File.Exists(path3) || System.IO.File.Exists(path4))
            {
                folder_copy1 = PATHCHON;
                return true;
            }
            else
            {
                msgbox.dialog_OK_warning("Không tìm thấy 2 file trong thư mục " + PATHCHON + "");

                return false;
            }
        }

        public void check_va_taothumuc_local()
        {
            string name = System.Environment.MachineName;
            string path = sql_file + @"\Date_deleted_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Hour.ToString() + "h" + DateTime.Now.Minute.ToString() + "(" + name + ")";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                folder_copy2 = path;
            }
            else
            {

                Directory.Delete(path);
                Directory.CreateDirectory(path);
                folder_copy2 = path;
            }
        }
        public void attach()
        {

            string A3 = folder_root + @"\ABC_Data.mdf";
            string A4 = folder_root + @"\ABC_Log.ldf";

            //string SQL2 = "exec sp_attach_db 'ABC', '" + A3 + "', '" + A4 + "'";
            //string S="CREATE DATABASE ABC ON (FILENAME = N'"+A3+"') FOR ATTACH;";
            //mt.T_exc(S);
            string SQL2 = "EXEC sp_attach_single_file_db @dbname='ABC',@physname=N'" + A3 + "'";
            mt.T_exc(SQL2);
        }
        public void detach()
        {
            string SQL = "sp_detach_db N'ABC'";




            string CLOSE1 = "ALTER DATABASE [ABC] SET OFFLINE WITH ROLLBACK IMMEDIATE";
            mt.T_exc(CLOSE1);


            mt.T_exc(SQL);
        }
        string folder_copy1, folder_copy2, folder_root;
        public void copy_thumucxoa()
        {

            string A3 = folder_root + @"\ABC_Data.mdf";
            string A4 = folder_root + @"\ABC_Log.ldf";



            System.IO.File.Copy(A3, folder_copy2 + @"\ABC_Data.mdf");
            //  System.IO.File.Copy(A4, folder_copy2 + @"\ABC_Log.ldf");
        }
        public void prelace_datacu()
        {

            string A3 = folder_root + @"\ABC_Data.mdf";
            string A4 = folder_root + @"\ABC_Log.ldf";

            System.IO.File.Delete(A3);
            System.IO.File.Delete(A4);

            if (System.IO.File.Exists(A4))
            {
                System.IO.File.Delete(A4);
            }
            else
            {
                string temp_A4 = folder_root + @"\ABC_Data_log.ldf";
                System.IO.File.Delete(temp_A4);
            }

            System.IO.File.Copy(folder_copy1 + @"\ABC_Data.mdf", A3);
            //System.IO.File.Copy( folder_copy1 + @"\ABC_Log.ldf",A4);

        }
    }
}
