using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using FMessegeBox;
using System.Data.SqlClient;
using System.Data;
using System.Threading;
using System.IO.Ports;
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication8
{
    class ClsSetting
    {
        Security s = new Security();

        private static string ModemPortName = "COM3";
        public static string ModemPortName_
        {
            get { return ModemPortName; }
            set { ModemPortName = value; }
        }

        private static string EmailUserid_;
        public static string EmailUserid
        {
            get { return EmailUserid_; }
            set { EmailUserid_ = value; }
        }

        private static string EmailPassword_;
        public static string EmailPassword
        {
            get { return EmailPassword_; }
            set { EmailPassword_ = value; }
        }

        private static string EmailDisplayname_;
        public static string EmailDisplayname
        {
            get { return EmailDisplayname_; }
            set { EmailDisplayname_ = value; }
        }
        
        private static bool ABackup = false;
        public static bool Backup_A
        {
            get { return ABackup; }
            set { ABackup = value; }
        }

        public void GetSettingInfo()
        {
            //گرفتن تنظیمات
            if (File.Exists(Application.StartupPath + "\\Setting.ini"))
            {
                string encrypt = File.ReadAllText(Application.StartupPath + "\\Setting.ini");
                string decrypt = s.Decrypt_Text(encrypt, Security.Password_);
                string[] decrypArray = decrypt.Split('\n');
                Security.PasswordProgram_ = decrypArray[0];
                ModemPortName = decrypArray[1];
                Backup_A = Convert.ToBoolean(decrypArray[2]);
                ConnectionInfo.ConnectionStringAttachDb = Convert.ToBoolean(decrypArray[3]);
                EmailUserid = decrypArray[4];
                EmailPassword = decrypArray[5];
                EmailDisplayname_ = decrypArray[6];
            }
        }

        public void SaveSettingInfo()
        {
            //ذخیره تنظیمات
            string write = Security.PasswordProgram_ +
                "\n" + ModemPortName_ +
                "\n" + Backup_A.ToString() +
                "\n" + ConnectionInfo.ConnectionStringAttachDb.ToString() +
                "\n" + EmailUserid +
                "\n" + EmailPassword +
                "\n" + EmailDisplayname_;

            string encrypt = s.Encrypt_Text(write, Security.Password_);
            File.WriteAllText(Application.StartupPath + "\\Setting.ini", encrypt);
        }

        public static bool CheckDB(string Database, string UserID, string Password)
        {
            try
            {
                SqlConnection con = new SqlConnection("Data Source=" + Database + ";Initial Catalog=master;user id=" + UserID + ";password=" + Password);
                con.Open();
                SqlCommand com = new SqlCommand("select * from sys.databases where name= 'Tell'", con);
                object obj = com.ExecuteScalar();
                con.Close();
                if (obj == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }

        }

        public static void BackupDatabase()
        {
            ConnectionInfo ConInfo = new ConnectionInfo();
            ConInfo.ConnectDB_Info();

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "*.bak|*.bak";
            saveFileDialog1.FileName = "Backup " + (DateIran(false)).Replace("/", ".");
            saveFileDialog1.InitialDirectory = Application.StartupPath + "\\SQL Backup";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(ConnectionInfo.ConnectionString))
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        SqlCommand cmd = new SqlCommand("backup database [" + ConInfo.InitialCatalog + "] to disk=@path with format", con);
                        cmd.Parameters.AddWithValue("@path", saveFileDialog1.FileName);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    Cursor.Current = Cursors.Default;
                    FarsiMessegeBox.Show("پشتیبانگیری با موفقیت انجام شد.", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
                }
                catch (Exception ex)
                {
                    //FarsiMessegeBox.Show("خطا در انجام پشتیبانگیری" + "\n" + ex.Message, "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
                    MessageBox.Show(ex.Message);
                }
            }
        }

        public static void BackupDatabase_A() //پشتیبانگیری به صورت خودکار
        {
            try
            {
                if (!System.IO.File.Exists(Application.StartupPath + "\\SQL Backup\\" + "Backup " + (ClsSetting.DateIran(false)).Replace("/", ".") + ".bak"))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    ConnectionInfo ConInfo = new ConnectionInfo();
                    ConInfo.ConnectDB_Info();
                    string path = Application.StartupPath + "\\SQL Backup\\" + "Backup " + (ClsSetting.DateIran(false)).Replace("/", ".") + ".bak";
                    using (SqlConnection con = new SqlConnection(ConnectionInfo.ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand("backup database [" + ConInfo.InitialCatalog + "] to disk=@path with format", con);
                        cmd.Parameters.AddWithValue("@path", path);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    Cursor.Current = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                FarsiMessegeBox.Show("خطا در انجام پشتیبانگیری خودکار" + "\n" + ex.Message, "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
            }
        }

        public static void RestoreDatabase()
        {
            ConnectionInfo ConInfo = new ConnectionInfo();
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "*.bak|*.bak";
            openFileDialog1.FileName = "";
            openFileDialog1.InitialDirectory = Application.StartupPath + "\\SQL Backup";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;

                    string query = "USE [master]; RESTORE DATABASE [" + ConInfo.InitialCatalog + "] FROM DISK = N'" +
                    openFileDialog1.FileName + " ' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10";

                    ConnectionInfo.QueryRun(query);

                    Cursor.Current = Cursors.Default;
                    FarsiMessegeBox.Show("برگرداندن اطلاعات با موفقیت انجام شد.", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
                }
                catch (Exception ex)
                {
                    FarsiMessegeBox.Show("خطا در برگرداندن اطلاعات" + "\n" + ex.Message, "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
                }
            }
        }

        public static void AtachDB()
        {
            try
            {
                if (Directory.Exists(Application.StartupPath + "\\SQL DataBase") && File.Exists(Application.StartupPath + "\\SQL DataBase\\Tell.mdf") && File.Exists(Application.StartupPath + "\\SQL DataBase\\Tell.ldf"))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    ConnectionInfo ConInfo = new ConnectionInfo();
                    ConInfo.ConnectFile();
                    SqlConnection con = new SqlConnection(ConnectionInfo.ConnectionString);
                    //SqlConnection con = new SqlConnection("Data Source=MEHRSA-D9C853CA\\MEHRSAPC;Initial Catalog=sa;User Id=sa;Password=123");
                    string cmdString = "EXEC sp_attach_db @dbname = N'Tell', @filename1 = N'" + Application.StartupPath + "\\SQL DataBase\\Tell.mdf" + "',@filename2 = N'" + Application.StartupPath + "\\SQL DataBase\\Tell.ldf" + "'";
                    SqlCommand cmd = new SqlCommand(cmdString, con);
                    cmd.Connection = con;
                    cmd.Connection.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();
                    if (dr.IsClosed == false)
                        dr.Close();
                    Cursor.Current = Cursors.Default;
                    FarsiMessegeBox.Show("بانک اطلاعاتی با موفقیت نصب گردید.", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
                }
                else
                {
                    FarsiMessegeBox.Show("فایل بانک اطلاعاتی وجود ندارد", "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
                }
            }
            catch (SqlException ex)
            {
                if (ex.ErrorCode == -2146232060)
                {
                    FarsiMessegeBox.Show("تنظیمات بانک اطلاعاتی اشتباه است", "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
                }
            }
            catch (Exception ex)
            {
                FarsiMessegeBox.Show(ex.Message, "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
            }
        }

        public static string ToPersianNumber(string input)
        {
            //۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹

            input = input.Replace("0", "۰");
            input = input.Replace("1", "۱");
            input = input.Replace("2", "۲");
            input = input.Replace("3", "۳");
            input = input.Replace("4", "۴");
            input = input.Replace("5", "۵");
            input = input.Replace("6", "۶");
            input = input.Replace("7", "۷");
            input = input.Replace("8", "۸");
            input = input.Replace("9", "۹");

            return input;
        }
        public static string DateIran(bool DayShow)
        {
            string date = "";
            System.Globalization.PersianCalendar p = new System.Globalization.PersianCalendar();
            date = p.GetYear(DateTime.Now).ToString() + "/" + p.GetMonth(DateTime.Now).ToString() + "/" + p.GetDayOfMonth(DateTime.Now).ToString();
            if (DayShow)
            {
                switch (DateTime.Now.DayOfWeek)
                {
                    case DayOfWeek.Friday:
                        date = "جمعه " + date;
                        break;
                    case DayOfWeek.Monday:
                        date = "دوشنبه " + date;
                        break;
                    case DayOfWeek.Saturday:
                        date = "شنبه " + date;
                        break;
                    case DayOfWeek.Sunday:
                        date = " یکشنبه " + date;
                        break;
                    case DayOfWeek.Thursday:
                        date = "دوشنبه " + date;
                        break;
                    case DayOfWeek.Tuesday:
                        date = "سه شنبه " + date;
                        break;
                    case DayOfWeek.Wednesday:
                        date = "چهارشنبه " + date;
                        break;
                }
            }
            return date;
        }
        public static bool ChPortModem(string PortName)
        {
            SerialPort port = new SerialPort();
            port.Close();
            try
            {
                port.PortName = PortName;
                port.Open();
                port.Write("AT\r");
                Thread.Sleep(200);
                if (port.ReadExisting().ToUpper().Contains("OK"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                port.Close();
            }

        }
        public static void DeleteNumber()
        {
            try
            {
                ConnectionInfo.QueryRun("Delete From TellTbl DBCC CHECKIDENT (TellTbl, RESEED, 0)");

                FarsiMessegeBox.Show("تمامی اطلاعات با موفقیت پاک شد.", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
            }
            catch (Exception ex)
            {
                FarsiMessegeBox.Show(ex.Message, "Error", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
            }
        }

        public static bool SendMessage(string subject, string messageBody, string fromAddress, string pass, string DisplayName, string toAddress,string attach)
        {
            try
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(fromAddress + "@gmail.com", DisplayName, Encoding.GetEncoding("windows-1256"));

                if (toAddress.Trim().Length > 0)
                {
                    foreach (string addr in toAddress.Split(','))
                    {
                        if (validatingEmail(addr.Trim()))
                        {
                            message.To.Add(new MailAddress(addr));
                        }
                    }
                }
                if (attach.Trim().Length > 0)
                {
                    foreach (string att in attach.Split(';'))
                    {
                        if (att.Trim().Length > 2)
                        {
                            message.Attachments.Add(new Attachment(att));
                        }
                    }
                }

                message.Subject = subject;
                message.Body = messageBody;
                SmtpClient smtp = new SmtpClient();
                smtp.Credentials = new NetworkCredential(fromAddress, pass);
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.Send(message);
                return true;
            }
            catch
            {
                return false;
            }

        }
        public static bool validatingEmail(string  email)
        {
            Regex rgx = new Regex(@"^([\w-]+\.)*?[\w-]+@[\w-]+\.([\w-]+\.)*?[\w]+$");
            return rgx.IsMatch(email);
        }
    }
}
