/*
        public static void initVLC()
        {
            if (Environment.Is64BitOperatingSystem)
            {
                // Set libvlc.dll and libvlccore.dll directory path
                VlcContext.LibVlcDllsPath = @"VLC\";

                // Set the vlc plugins directory path
                VlcContext.LibVlcPluginsPath = @"VLC\plugins";
            }
            else
            {
                // Set libvlc.dll and libvlccore.dll directory path
                VlcContext.LibVlcDllsPath = @"VLC\";

                // Set the vlc plugins directory path
                VlcContext.LibVlcPluginsPath = @"VLC\plugins";
            }

            // Ignore the VLC configuration file
            VlcContext.StartupOptions.IgnoreConfig = true;
#if DEBUG
            // Enable file based logging
            VlcContext.StartupOptions.LogOptions.LogInFile = true;

            // Shows the VLC log console (in addition to the applications window)
            VlcContext.StartupOptions.LogOptions.ShowLoggerConsole = true;
#else
            VlcContext.StartupOptions.LogOptions.ShowLoggerConsole = false;
            VlcContext.StartupOptions.LogOptions.LogInFile = false;
#endif
            // Set the log level for the VLC instance
            VlcContext.StartupOptions.LogOptions.Verbosity = VlcLogVerbosities.Debug;
            VlcContext.StartupOptions.AddOption("--ffmpeg-hw");
            // Disable showing the movie file name as an overlay
            VlcContext.StartupOptions.AddOption("--no-video-title-show");
            VlcContext.StartupOptions.AddOption("--rtsp-tcp");
            VlcContext.StartupOptions.AddOption("--rtsp-mcast");
            // VlcContext.StartupOptions.AddOption("--rtsp-host=192.168.10.35");
            // VlcContext.StartupOptions.AddOption("--sap-addr=192.168.10.35");
            VlcContext.StartupOptions.AddOption("--rtsp-port=8554");
            VlcContext.StartupOptions.AddOption("--rtp-client-port=8554");
            VlcContext.StartupOptions.AddOption("--sout-rtp-rtcp-mux");
            VlcContext.StartupOptions.AddOption("--rtsp-wmserver");


            VlcContext.StartupOptions.AddOption("--file-caching=18000");
            VlcContext.StartupOptions.AddOption("--sout-rtp-caching=18000");
            VlcContext.StartupOptions.AddOption("--sout-rtp-port=8554");
            VlcContext.StartupOptions.AddOption("--sout-rtp-proto=tcp");
            VlcContext.StartupOptions.AddOption("--network-caching=1000");

            VlcContext.StartupOptions.AddOption("--vout-filter=wall");
            VlcContext.StartupOptions.AddOption("--wall-cols=2");
            VlcContext.StartupOptions.AddOption("--wall-rows=2");

            // Pauses the playback of a movie on the last frame
            VlcContext.StartupOptions.AddOption("--play-and-pause");
            VlcContext.CloseAll();
            // Initialize the VlcContext
            VlcContext.Initialize();
        }
        */

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            bool login = true;
            Rows = new List<CsvRow>();
            RowsSend = new List<CsvRow>();
            Fonts = ExCss.ReadFile(@"Asset\Fonts\font-awesome.min.css");
            Timethread = new Thread(CheckTimeFunctionThread);
            Timethread.IsBackground = true;
            listSerialPort = new List<SerialPort>();
            QueueCMD = new Queue<string>();
            m_bInitSDK = CHCNetSDK.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                MessageBox.Show("NET_DVR_Init error!");
                return;
            }
            if (!File.Exists(_FILE_CSV_COMMAND))
            {
                File.Create(_FILE_CSV_COMMAND);
            }
            if (!File.Exists(_FILE_Send_COMMAND))
            {
                File.Create(_FILE_Send_COMMAND);
            }
            //  initVLC();
            DefineCommand = CommandDefine.Read(_FILE_DEFINE_COMMAND);
            setting = Config.Read(_FILE_Config);
            if (!Directory.Exists("Data"))
            {
                DirectoryInfo di = Directory.CreateDirectory("Data");
                di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
            }
            if (!Directory.Exists(setting.Folder))
            {
                Directory.CreateDirectory(setting.Folder);
            }
            curDate = DateTime.Now;
            Timethread.Start();
            curFolder = System.IO.Path.Combine(setting.Folder, this.curDate.ToString("dd-MM-yyyy"));
            if (!Directory.Exists(curFolder))
            {
                Directory.CreateDirectory(curFolder);
            }
            DataUser = Users.read(@"Data\User.mtc");
            if (DataUser == null)
            {
                DataUser = new Users();
                User root = new User("root", 1);
                root.Pass = "******".toMD5();
                root.type = 0;
                root.FullName = "Root";
                DataUser.Add(root);
                Users.write(_FILE_User_Data, DataUser);
            }
            DataCamera = Cameras.Read(_FILE_Camera_Data);
            DataPreset = Presets.Read(_FILE_PRESET_DATA);
            DataAlarm = Alarms.Read(_FILE_Alarm_Data);
            this.checkFile = new Thread(checkFileFunctionThread);
            checkFile.IsBackground = true;
            this.checkFile.Start();
#if DEBUG
            if (DataCamera.Count == 0)
            {
                Camera camera = new Camera("192.168.10.199");
                camera.name = "Camera Demo";
                camera.channel = 1;
                camera.port = 8000;
                camera.admin = "admin";
                camera.pass = "******";
                camera.icon = "fa-video-camera";
                DataCamera.Add(camera);
            }
            
            if (DataUser.Datas.Count < 2)
            {
                User root = new User("admin", 2);
                root.Pass = "******".toMD5();
                root.type = 1;
                root.FullName = "Admin";
                DataUser.Add(root);

                User root2 = new User("htdm",3);
                root2.Pass = "******".toMD5();
                root2.type = 2;
                root2.FullName = "Camera";
                DataUser.Add(root2);
                Users.write(_FILE_User_Data, DataUser);
            }
            
#endif
            var listCom = getListCOM();
            if (listCom.Length > 0)
            {
                foreach (string i in listCom)
                {
                    try
                    {
                        SerialPort serialPort = new SerialPort();
                        serialPort = new SerialPort();
                        serialPort.openCOM(i, BAUDRATE, DATABITS, StopBits.One);
                        serialPort.DataReceived += serialPort_DataReceived;
                        serialPort.sendCommand("#0$");
                        listSerialPort.Add(serialPort);
                    }
                    catch (Exception)
                    {

                    }
                }

            }
            Map = Map.Read(_FILE_Map_Data);
            for (int i = 0; i != e.Args.Length; i += 2)
            {
                if (e.Args[i] == "-u")
                {
                    string hash = e.Args[i + 1];
                    User u = App.DataUser.Login(hash);
                    if (u != null)
                    {
                        login = false;
                        App.User = u;
                    }
                }
                else if (e.Args[i] == "-mode")
                {
                    Mode = (Camera_Final.Mode)int.Parse(e.Args[i + 1]);
                }
            }
            if (login)
            {
                this.MainWindow = new Login();
            }
            else
            {
                this.MainWindow = new MainWindow();
            }
            this.MainWindow.Show();
        }
 public static void write(string filename, Users data)
 {
     using (RijndaelManaged RMCrypto = new RijndaelManaged())
     {
         byte[] Key = ("Teppy@MTC_1.0_2015").toMD5().Clone(0.5f).toBytes();
         byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x32, 0x06, 0x07, 0x08, 0x92, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x76 };
         RMCrypto.Mode = CipherMode.CBC;
         //byte[] input = data.toByteArray();
         if (!File.Exists(filename))
         {
             using (Stream s = File.Open(filename, FileMode.OpenOrCreate))
             {
                 using (CryptoStream CryptStream = new CryptoStream(s, RMCrypto.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
                 {
                     BinaryFormatter formatter = new BinaryFormatter();
                     formatter.Serialize(CryptStream, data);
                     CryptStream.FlushFinalBlock();
                     CryptStream.Close();
                 }
                 s.Close();
             }
         }
         else
         {
             using (Stream s = File.Open(filename, FileMode.Truncate))
             {
                 using (CryptoStream CryptStream = new CryptoStream(s, RMCrypto.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
                 {
                     BinaryFormatter formatter = new BinaryFormatter();
                     formatter.Serialize(CryptStream, data);
                     CryptStream.FlushFinalBlock();
                     CryptStream.Close();
                 }
                 s.Close();
             }
         }
     }
 }