using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using Maser.Feanor.Model;
using Maser.Feanor.Biz;
using Maser.Feanor.MIDSInterface;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Data.SqlClient;

namespace FeanorProjects
{
    public partial class FeanorProjects : Form
    {
        //private const string BuildInformation = "Palantir - Project Manager";
        private const string PathToAnalysisTool = @"C:\META\META.exe";  // Location of META, place META folder (with META.exe) in C-drive!

        // The dgv content always corresponds to _ProjectsContent.
        ObservableCollection<Project> _ProjectsContent = new ObservableCollection<Project>();

        // The listboxes with chambers always corresponds to _ChambersContent. 
        ObservableCollection<Chamber> _ChambersContent = new ObservableCollection<Chamber>();
        Boolean[] _ChambersContentSelected;

        // The listboxes with Sensor always corresponds to _SensorsContent.
        ObservableCollection<Sensor> _SensorsContent = new ObservableCollection<Sensor>();
        Boolean[] _SensorsContentSelected;

        Project _Project = new Project();
        Chamber _Chamber = new Chamber();

        bool CMS2PC = true;

        public FeanorProjects()
        {

            try
            {

                using (SqlConnection connection = new SqlConnection("Data Source=tcp:10.126.21.47\\FEANOR,1434; Initial Catalog=FEANOR; User ID=sa; Password=resam@123resam; timeout=15; Persist Security Info=True; TrustServerCertificate=True"))
                {
                    connection.Open();
                    Console.WriteLine("Succesvolle verbinding!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fout bij verbinden: " + ex.Message);
            }

            InitializeComponent();

            try
            {
                string hostName = Dns.GetHostName(); // retrieve host name
                Console.WriteLine(hostName);
                if (hostName != "MEEU010LAB00003") // only show NodeStatus button for CMS2 PC
                    CMS2PC = false;
                
            }
            catch { }

            _ProjectsContent.CollectionChanged += projects_CollectionChanged;
            _ChambersContent.CollectionChanged += chambers_CollectionChanged;
            _SensorsContent.CollectionChanged += sensors_CollectionChanged;

            System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly(); // report build version 
            string exe = System.IO.Path.GetFullPath(ass.Location);
            DateTime dt = new System.IO.FileInfo(exe).LastWriteTimeUtc;
            this.Text =  String.Format("Feanor - Projects" + "   v{0:0000}{1:00}{2:00}", dt.Year, dt.Month, dt.Day);
        }

        public Project SelectedProject
        {
            
            get
            {
                int i;
                try
                {
                    if(dgvProjects.Rows.Count >0)
                    {
                        i = dgvProjects.CurrentCell.RowIndex;
                    }
                    else
                    {
                        return null;
                    }
                    
                }
                catch { i = -1; }

                if (i < 0)
                    return null;

                return _ProjectsContent[i];
            }
        }


        void projects_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            dgvProjects_Populate();
        }

        void chambers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            lboxChambers_Populate();
            _ChambersContentSelected = new bool[_ChambersContent.Count];
        }

        void sensors_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            dgvSensors_Populate();
            _SensorsContentSelected = new bool[_SensorsContent.Count];
        }

        private void FeanorProjects_Load(object sender, EventArgs e)
        {
            #region Center the form
            int w = Screen.PrimaryScreen.Bounds.Width;
            int h = Screen.PrimaryScreen.Bounds.Height;
            int x = (int)Math.Max(0, Math.Ceiling(0.5 * w - 0.5 * this.Width));
            int y = (int)Math.Max(0, Math.Ceiling(0.5 * h - 0.5 * this.Height));
            this.Location = new Point(x, y);
            #endregion Center the form

            pnlNewProject.Location = new Point(0,  menu.Height);
            pnlNewProject.Size = new Size(1260, 894);
            pnlViewProjects.Location = new Point(0, menu.Height);
            pnlViewProjects.Size = new Size(1260, 894);
            pnlExport.Location = new Point(0, menu.Height);
            pnlExport.Size = new Size(1260, 894);

            // Datagridview is not sortable. Content shall be consistant with ordering in var dgvProjectsContent
            foreach (DataGridViewColumn dCol in dgvProjects.Columns)
                dCol.SortMode = DataGridViewColumnSortMode.NotSortable;
            dgvProjects.Columns[0].Width = 130;
            dgvProjects.Columns[1].Width = 80;
            dgvProjects.Columns[2].Width = 300;
            dgvProjects.Columns[3].Width = 200;
            dgvProjects.Columns[4].Width = 170;
            

            // datagridview dgvLinkChambers
            dgvLinkChambers.Columns[0].Width = dgvLinkChambers.Width - 2;
            dgvLinkChambers.ScrollBars = ScrollBars.Vertical;
            dgvLinkChambers.DefaultCellStyle.ForeColor = Color.LightGray;
            dgvLinkChambers.DefaultCellStyle.SelectionForeColor = Color.Black;
            dgvLinkChambers.DefaultCellStyle.SelectionBackColor = dgvLinkChambers.DefaultCellStyle.BackColor;
            dgvLinkChambers.BackgroundColor = dgvLinkChambers.DefaultCellStyle.BackColor;
            dgvLinkChambers.CellBorderStyle = DataGridViewCellBorderStyle.None;

            // datagridview dgvSensors
            dgvSensors.Columns[0].Width = dgvSensors.Width - 2;
            dgvSensors.ScrollBars = ScrollBars.Vertical;
            dgvSensors.DefaultCellStyle.ForeColor = Color.LightGray;
            dgvSensors.DefaultCellStyle.SelectionForeColor = Color.Black;
            dgvSensors.DefaultCellStyle.SelectionBackColor = dgvSensors.DefaultCellStyle.BackColor;
            dgvSensors.BackgroundColor = dgvSensors.DefaultCellStyle.BackColor;
            dgvSensors.CellBorderStyle = DataGridViewCellBorderStyle.None;

            // Shortcuts to menu
            menuViewFind.ShortcutKeys = Keys.F3;
            menuNewProject.ShortcutKeys = Keys.F4;
            menuViewInProgress.ShortcutKeys = Keys.F5;
            menuViewFinished.ShortcutKeys = Keys.F6;
            menuViewAll.ShortcutKeys = Keys.F7;

            // Start current UTC clock update timer
            timerUtcClock.Start(); timerUtcClock_Tick(null, null);

            // Go to start screen
            ShowProjects(ProjectStatus.InProgress);
        }


        private void ShowProjects(ProjectStatus pStatus)
        {
            //gbProjectDetails.Visible = false;
            
            pnlViewProjects.BringToFront();

            // List projects in dgv
            List<Project> projects = new List<Project>();
            try
            {
                List<Project> list;
                switch (pStatus)
                {
                    case ProjectStatus.Finished:
                        list = new Projects().GetAllFinished();                        
                        gbProjectList.Text = String.Format("Finished projects ({0})", list.Count);                      
                        break;
                    case ProjectStatus.InProgress:
                        list = new Projects().GetAllActive();
                        gbProjectList.Text = String.Format("Projects in progress ({0})", list.Count);                        
                        break;
                    case ProjectStatus.FinishedLastMonth:
                        list = new Projects().GetAllFinishedLastMonth();
                        gbProjectList.Text = String.Format("Projects finished last month ({0})", list.Count);
                        break;
                    case ProjectStatus.FinishedLastWeek:
                        list = new Projects().GetAllFinishedLastWeek();
                        gbProjectList.Text = String.Format("Projects finished last week ({0})", list.Count);
                        break;
                    default:
                        list = new Projects().GetAll();
                        gbProjectList.Text = String.Format("Projects ({0})", list.Count);                       
                        break;
                }
                _ProjectsContent.CollectionChanged -= projects_CollectionChanged; // Unsubscribe to prevent reoccuring firing
                _ProjectsContent.Clear();
                foreach (Project p in list)
                {
                    _ProjectsContent.Add(p);                    
                }
                    
            }
            catch(Exception ex)
            {
                MessageBox.Show("Could not retrieve projects from database!" + ex.Message, "Projects", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _ProjectsContent.Clear();
            }
            finally
            {
                // Subscribe again and fire              
                _ProjectsContent.CollectionChanged += projects_CollectionChanged;
                projects_CollectionChanged(null,null);               
            }
            //dgvProjects.ClearSelection();
        }


        private void dgvProjects_Populate()
        {
            lbChamberConditions.Items.Clear();
            if (_ProjectsContent == null)
            {
                gbProjectList.Text = "Projects (0)";
                dgvProjects.Rows.Clear();
                return;
            }
            if (_ProjectsContent.Count == 0)
            {
                gbProjectList.Text = "Projects (0)";
                dgvProjects.Rows.Clear();
                return;
            }

            // Remove enough rows or add missing ones
            while (dgvProjects.Rows.Count > _ProjectsContent.Count)
                dgvProjects.Rows.RemoveAt(0);
            if(dgvProjects.Rows.Count < _ProjectsContent.Count)
                dgvProjects.Rows.Add(_ProjectsContent.Count- dgvProjects.Rows.Count);


            Chambers cBiz = new Chambers();
            String c = "";

            for (int i = 0; i < _ProjectsContent.Count; i++)
            {
                // Project info
                Project p = _ProjectsContent[i];
               
                if(p.ProjectDescription == "Maintenance and calibration")
                {
                    dgvProjects[0, i].Value = String.Format("I{0:00000} sub {1:00} step {2:00}", p.ProjectID, p.SubProject, p.Step);
                }
                else
                {
                    dgvProjects[0, i].Value = String.Format("P{0:00000} sub {1:00} step {2:00}", p.ProjectID, p.SubProject, p.Step);
                }


                dgvProjects[2, i].Value = p.StepDescription;               
                dgvProjects[4, i].Value = p.Customer;
                //dgvProjects[5, i].Value = String.Format("{0:0}h", p.TotalTime);

                // Duration
                double min = p.Stop == null ? (Time.UTC - p.Start).TotalMinutes : ((DateTime)p.Stop - p.Start).TotalMinutes;
                double hrs = Math.Floor(min / 60);
                min -= hrs * 60;
                dgvProjects[1, i].Value = String.Format("{0:0}h{1:0}", hrs, min);

                // Chamber description
                try { c = cBiz.GetByPK(p.Chamber).MIDSandDescription; } catch { c = "Chamber not found!"; }
                dgvProjects[3, i].Value = c;

                dgvProjects.Rows[i].DefaultCellStyle.ForeColor = System.Drawing.SystemColors.ControlText;

                try
                {                    
                    Color rowColor = MIDSinterface.RowColor(cBiz.GetByPK(p.Chamber).MIDS);      // obtain row color (from MIDS) for each chamber                   
                    dgvProjects.Rows[i].DefaultCellStyle.BackColor = rowColor;                
                }
                catch { }
            }                        
        }

        private void lboxChambers_Populate() // Lijst met actieve kamers
        {
            // Handles lboxChambersNew, lboxChambersDetails & dgvLinkChambers
            lboxChambersNew.Items.Clear();
            lboxChambersDetails.Items.Clear();

            if (_ChambersContent == null)
            {
                gbNewChamber.Text = "Chambers (0)";
                return;
            }
                
            // Update all listboxes containing chambers info.
            foreach (Chamber c in _ChambersContent)
            {
                lboxChambersNew.Items.Add(c.MIDSandDescription);
                lboxChambersDetails.Items.Add(c.MIDSandDescription);
            }
            gbNewChamber.Text = string.Format("Chambers ({0})", _ChambersContent.Count);


            // dgvLinkChambers
            //this.dgvLinkChambers.SelectionChanged -= new System.EventHandler(this.dgvLinkChambers_SelectionChanged);
            while (dgvLinkChambers.Rows.Count > 0)
                dgvLinkChambers.Rows.RemoveAt(0);

            if (_ChambersContent.Count > 0)
                dgvLinkChambers.Rows.Add(_ChambersContent.Count);

            for (int i = 0; i < _ChambersContent.Count; i++)
                dgvLinkChambers[0, i].Value = _ChambersContent[i].MIDSandDescription;
            //this.dgvLinkChambers.SelectionChanged += new System.EventHandler(this.dgvLinkChambers_SelectionChanged);
        }

        private void dgvSensors_Populate()
        {
            if (_SensorsContent == null)
            {
                dgvSensors.Rows.Clear();
                return;
            }
            if (_SensorsContent.Count == 0)
            {
                dgvSensors.Rows.Clear();
                return;
            }

            // Remove enough rows or add missing ones
            while (dgvSensors.Rows.Count > _SensorsContent.Count)
                dgvSensors.Rows.RemoveAt(0);
            if (dgvSensors.Rows.Count < _SensorsContent.Count)
                dgvSensors.Rows.Add(_SensorsContent.Count - dgvSensors.Rows.Count);

            for (int i = 0; i < _SensorsContent.Count; i++)
            {
                dgvSensors[0, i].Value = _SensorsContent[i].ListDescription;
                //Console.WriteLine(_SensorsContent[i].ListDescription);
            }                
        }


        private void ShowPanelNewProject()
        {           
            pnlNewProject.BringToFront();
            lbNewStepSelectList.Items.Clear();
            lbNewSubProjectSelectList.Items.Clear();

            // List chambers
            try
            {
                List<Chamber> chambers = new Chambers().GetAllActive();     // All chambers where active == 1
               
                _ChambersContent.CollectionChanged -= chambers_CollectionChanged;
                _ChambersContent.Clear();
                foreach (Chamber c in chambers)
                {
                    _ChambersContent.Add(c);                                // Add all chambers                     
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not retrieve chambers from database!" + ex.Message, "Projects", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _ChambersContent.Clear();
            }

            finally
            {
                txtbNewProjectNumber.Text = "";
                txtbNewSubprojectNumber.Text = "";
                txtbNewStepNumber.Text = "";
                cboxInvProject.Checked = false;
                txtbNewCustomerDescription.Text = "";
                txtbNewProjectDescription.Text = "";
                txtbNewSubProjectDescription.Text = "";
                txtbNewStepDescription.Text = "";
                txtbChamberNumber.Text = "";


                // Subscribe again and fire
                _ChambersContent.CollectionChanged += chambers_CollectionChanged;
                chambers_CollectionChanged(null, null);                                     // Update chambers list
            }
        }


        private void btnNewProjectFindMIDS_Click(object sender, EventArgs e) // FIND button
        {
            // retreive data inputted by user            
            string projectnumb;
            string subprojectnumb;
            string stepnumb;

            // Remove 'P' or 'p' and 'I' or 'i' from projectnumber
            string NewProjectNumber = txtbNewProjectNumber.Text;
            if (NewProjectNumber.StartsWith("p") || NewProjectNumber.StartsWith("P") || NewProjectNumber.StartsWith("i") || NewProjectNumber.StartsWith("I"))
            {
                projectnumb = NewProjectNumber.Substring(1);
            }


            if (txtbNewProjectNumber.Text != "")
            {
                projectnumb = txtbNewProjectNumber.Text;
            }
            else
            {
                MessageBox.Show("Please input project number");
                return;
            }
            if (txtbNewSubprojectNumber.Text != "")
            {
                subprojectnumb = txtbNewSubprojectNumber.Text;
            }
            else
            {
                MessageBox.Show("Please input sub project number");
                return;
            }
            if (txtbNewStepNumber.Text != "")
            {
                stepnumb = txtbNewStepNumber.Text;
            }
            else
            {
                MessageBox.Show("Please input step number");
                return;
            }


            if(cboxInvProject.Checked == true) // INV project
            {
                Console.WriteLine("Inventory Project (I)");

                try
                {
                    Project p = MIDSinterface.GetINVProject(Int32.Parse(projectnumb), Int32.Parse(subprojectnumb), Int32.Parse(stepnumb));

                    // onderstaande is wat het programma nodig heeft!
                    txtbNewCustomerDescription.Text = p.Customer;
                    txtbNewProjectDescription.Text = p.ProjectDescription;
                    txtbNewSubProjectDescription.Text = p.SubProjectDescription;
                    txtbNewStepDescription.Text = p.StepDescription;


                    // Pre-Select chamber from planning in MIDS

                    string chamberNumb = projectnumb.ToString().Substring(2);
                    Console.WriteLine("chambernumb");
                    Console.WriteLine(chamberNumb);
                   
                    Chamber plannedChamber = MIDSinterface.GetPlannedINVChamber(Int32.Parse(projectnumb), Int32.Parse(subprojectnumb), Int32.Parse(stepnumb));
                    Console.WriteLine("Planned: ");
                    Console.WriteLine(plannedChamber.MIDS);

                    try // find planned chamber in MIDS
                    {
                        for (int i = 0; i < lboxChambersNew.Items.Count; i++)
                        {
                            Chamber c = _ChambersContent[i];
                            Console.WriteLine(c.MIDS);
                                
                                if (c.MIDS == Int32.Parse(chamberNumb)) // if (c.MIDS == Int32.Parse(chamberNumb))
                                {
                                    lboxChambersNew.SelectedIndex = i;
                                   
                                    break;
                                }
                           // }
                        }

                        txtbChamberNumber.Text = chamberNumb;
                    }
                    catch
                    {
                        // do nothing
                        Console.WriteLine("error during retrieving (I) data");
                    }
                }
                catch
                {
                    txtbNewCustomerDescription.Text = "n/a";
                    txtbNewProjectDescription.Text = "n/a";
                    txtbNewSubProjectDescription.Text = "n/a";
                    txtbNewStepDescription.Text = "n/a";
                    Console.WriteLine("error during retrieving (I) data");
                }


            }
            else // P project
            {
                try
                {
                    // get project data from MIDS
                    _Project = MIDSinterface.GetProject(int.Parse(projectnumb), int.Parse(subprojectnumb), int.Parse(stepnumb));

                    _Chamber = MIDSinterface.GetPlannedChamber(int.Parse(projectnumb), int.Parse(subprojectnumb), int.Parse(stepnumb));

                    txtbChamberNumber.Text = _Chamber.MIDS.ToString();

                    Console.WriteLine("Planned: ");
                    Console.WriteLine(_Chamber.MIDS);

                    // output project number, subproject numer and step
                    txtbNewProjectNumber.Text = projectnumb;
                    txtbNewSubprojectNumber.Text = subprojectnumb;
                    txtbNewStepNumber.Text = stepnumb;

                    // output project descriptions
                    txtbNewCustomerDescription.Text = _Project.Customer;
                    txtbNewProjectDescription.Text = _Project.ProjectDescription;
                    txtbNewSubProjectDescription.Text = _Project.SubProjectDescription;
                    txtbNewStepDescription.Text = _Project.StepDescription;


                    Console.WriteLine("find planned chamber in MIDS");
                    try // find planned chamber in MIDS
                    {
                        for (int i = 0; i < lboxChambersNew.Items.Count; i++)
                        {
                            Chamber c = _ChambersContent[i];                          

                            Console.WriteLine(c.MIDS);

                            
                            if (_Chamber.MIDS == 0) // if no planned chamber from mids --> not possible to select chamber
                            {                               
                                    break;                                
                            }
                            else // get planned chamber from mids
                            {                                
                                if (c.MIDS == _Chamber.MIDS) // if (c.MIDS == Int32.Parse(chamberNumb))
                                {
                                    lboxChambersNew.SelectedIndex = i;

                                    break;
                                }
                            }
                            
                        }

                        
                    }
                    catch
                    {
                        // do nothing
                        Console.WriteLine("error during matching chambers");
                    }

                    


                }
                catch
                {
                    txtbNewCustomerDescription.Text = "n/a";
                    txtbNewProjectDescription.Text = "n/a";
                    txtbNewSubProjectDescription.Text = "n/a";
                    txtbNewStepDescription.Text = "n/a";
                    Console.WriteLine("error during retrieving (P) data");
                }

            }



            

            
        }


        private void btnStartNewProject_Click(object sender, EventArgs e) // START button
        {
            
            int project = 0;
            if (!Int32.TryParse(txtbNewProjectNumber.Text, out project))
                return;

            int sub = 0;
            if (!Int32.TryParse(txtbNewSubprojectNumber.Text, out sub))
                return;

            int step = 0;
            if (!Int32.TryParse(txtbNewStepNumber.Text, out step))
                return;

            string projectDescr = txtbNewProjectDescription.Text;           
            if (projectDescr.Length < 4)
            {
                MessageBox.Show("Project/sub/step does not exist");
                return;
            }

            string subDescr = txtbNewSubProjectDescription.Text;
            if (subDescr.Length < 4)
            {
                MessageBox.Show("Project/sub/step does not exist");
                return;
            }

            string stepDescr = txtbNewStepDescription.Text;
            if (stepDescr.Length < 4)
            {
                MessageBox.Show("Project/sub/step does not exist");
                return;
            }

            string customer = txtbNewCustomerDescription.Text;
            if (customer.Length < 2)
            {
                MessageBox.Show("Project/sub/step does not exist");
                return;
            }

            if (lboxChambersNew.SelectedIndex < 0) // if there is no chamber selected
            {
                MessageBox.Show("No chamber selected!\n", "New project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Selected chamber from list
            Chamber chamber = _ChambersContent[lboxChambersNew.SelectedIndex];

            
            if(stepDescr.Length > 250)
            {
                stepDescr = stepDescr.Substring(0, 254);
            }

           
            int TotalTime = 12345;
            
            // Create new project
            // format: Project(Int32 PK, Int32 chamber, DateTime start, DateTime? stop, Int32? ProjectID, String ProjectDescription, Int32? SubProject, String SubProjectDescription, Int32? Step, String StepDescription, String CustomerDescription)
            Project P = new Project(-1, chamber.PK, Time.UTC - new TimeSpan(0,5,0), null, project, projectDescr, sub, subDescr, step, stepDescr, customer,TotalTime);


            if (cboxInvProject.Checked == true) // Inventory project (I)
            {

                Console.WriteLine(chamber.MIDS);

                Console.WriteLine(subDescr.ToString());
                string checkSub = subDescr.Substring(0); // was 0,11
                Console.WriteLine(checkSub);
                string devID = project.ToString();
                devID = devID.Substring(2);
                Console.WriteLine("DevID:");
                Console.WriteLine(devID);


                if (checkSub == "Calibration")
                {
                    
                    Console.WriteLine("Calibration");
                    Console.WriteLine(String.Format("Z:\\inventory\\{0:00000}\\calibration\\{1}.{2} calibration", Int32.Parse(devID), project, sub));

                    if (!Directory.Exists(String.Format("Z:\\inventory\\{0:00000}\\calibration", Int32.Parse(devID), project, project, sub)))
                    {
                        DialogResult dr_path = MessageBox.Show("The inventory project folder is not found.\nAre you sure the project information is correct?", "New project", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                        if (dr_path != DialogResult.Yes)
                        {
                            return;
                        }
                    }
                }
                else // service project
                {
                    Console.WriteLine("Service");
                    Console.WriteLine(String.Format("Z:\\inventory\\{0:00000}\\service", Int32.Parse(devID), project, sub));


                    if (!Directory.Exists(String.Format("Z:\\inventory\\{0:00000}\\service", Int32.Parse(devID), project, sub)))
                    {
                        DialogResult dr_path = MessageBox.Show("The inventory project folder is not found.\nAre you sure the project information is correct?", "New project", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                        if (dr_path != DialogResult.Yes)
                        {
                            return;
                        }
                    }

                }
            }
            else
            {
                Console.WriteLine("Check directory for Project (P)");
                // Check if map exists on server, if not is project info ok?
                Int32 Year = (Int32)Math.Floor((double)project / 10000) + 2000;
                Console.WriteLine((String.Format("Z:\\projects\\{0}\\P{1:00000}\\sub{2}", Year, project, sub)));
                if (!Directory.Exists(String.Format("Z:\\projects\\{0}\\P{1:00000}\\sub{2}",Year, project, sub)))
                {
                    DialogResult dr_path = MessageBox.Show("The project folder is not found.\nAre you sure the project information is correct?", "New project", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                    if (dr_path != DialogResult.Yes)
                    {
                        return;
                    }
                }
            }





            try
            {
                P.PK = new Projects().Add(P);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not start project!\n\n" + ex.Message, "New project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Refresh dgvProjectsContent and select project in current project list.
            ShowProjects(ProjectStatus.InProgress);
            for(int i =0;i<_ProjectsContent.Count;i++)
            {
                if (_ProjectsContent[i].PK == P.PK)
                {
                    dgvProjects.Rows[i].Selected = true;
                    dgvProjects_MouseClick(null, null);
                    break;
                }
            }
            gbProjectDetails.Visible = false;
        }


        private void dgvProjects_MouseClick(object sender, MouseEventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();

            


            if (SelectedProject == null)                // if no project is selected
            {
                gbProjectDetails.Visible = false;
            }
            else
            {
                Console.WriteLine("selected "+ SelectedProject.ProjectID.ToString());
                Console.WriteLine(dgvProjects.CurrentCell.RowIndex.ToString());
                Console.WriteLine(_ProjectsContent[dgvProjects.CurrentCell.RowIndex].ProjectID.ToString());


                // if project is selected         
                ShowProjectDetails(SelectedProject);
                gbProjectDetails.Visible = true;

                if (SelectedProject.Stop != null)       // if project is finished
                {
                    btnStopReReset.Visible = true;
                }
                else
                {
                    btnStopReReset.Visible = false;
                }                                                      
            }           
        }

        private void ShowProjectDetails(Project project)
        {
            lbChamberConditions.Items.Clear();
            // Labels           
            if (project.ProjectDescription == "Maintenance and calibration")
            {
                ProjectIDlabel.Text = string.Format("I{0:000000}\n\n", project.ProjectID);
            }
            else
            {
                ProjectIDlabel.Text = string.Format("P{0:000000}\n\n", project.ProjectID);
            }
                
            ProjectSubLabel.Text = string.Format("Sub {0:0}\n", project.SubProject);
            ProjectStepLabel.Text = string.Format("Step {0:0}\n", project.Step);

            ProjectCustomerLabel.Text = project.Customer;
            ProjectDescriptionLabel.Text = project.ProjectDescription;
            SubProjectLabel.Text = project.SubProjectDescription;

            StepLabel.Text = project.StepDescription;

            // Duration
            Double hrs = (project.Stop == null) ? (Time.UTC - project.Start).TotalHours : ((DateTime)project.Stop - project.Start).TotalHours;
            string duration = "";
            if (hrs < 0)
                duration = "Stop is before start!";
            else
            {
                double h = Math.Floor(hrs);
                double m = Math.Floor(60 * (hrs - h));
                duration = String.Format("{0} hours and {1:00} minutes ", h, m);
                duration += (project.Stop == null) ? "(in progress)" : "(finished)";
            }
            // lblProjectInfoDescriptions.Text += "\n" + duration;
            DurationLabel.Text = duration;

            // Start and stop timestamps. NB: Stop is also updated by timer if project.stop == null
            dtpStartTime.Value = Time.UtcToLocal(project.Start);
            dtpStartDate.Value = Time.UtcToLocal(project.Start);

            //dtpStopTime.Value = (project.Stop == null) ? Time.Local : (DateTime)project.Stop;   // <-- original
            dtpStopTime.Value = (project.Stop == null) ? Time.Local : Time.UtcToLocal((DateTime)project.Stop);
            dtpStopDate.Value = (project.Stop == null) ? Time.Local : Time.UtcToLocal((DateTime)project.Stop);
          
            btnStopReset.Text = (project.Stop == null) ? "Set" : "Change";

            // Show available chambers and select current
            Chamber chamber = new Chamber();
            try
            {
                List<Chamber> chambers = new Chambers().GetAllActive();
                _ChambersContent.CollectionChanged -= chambers_CollectionChanged;
                _ChambersContent.Clear();
                foreach (Chamber c in chambers)
                    _ChambersContent.Add(c);
                chambers_CollectionChanged(null, null); // Fire to update

                for (int i=0;i<_ChambersContent.Count;i++)
                {
                    if(_ChambersContent[i].PK == project.Chamber)
                    {
                        chamber = _ChambersContent[i];
                        lboxChambersDetails.SelectedIndex = i;
                        break;
                    }
                }
                gbChamber.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not retrieve chambers from database!" + ex.Message, "Projects", MessageBoxButtons.OK, MessageBoxIcon.Error);
                gbChamber.Enabled = false;
                _ChambersContent.Clear();
            }

            finally
            {
                // Subscribe again
                _ChambersContent.CollectionChanged += chambers_CollectionChanged;
            }



            // Warnings
            List<string> warnings = new List<string>();
            try
            {
                List<Sensor> sensors = new Sensors().GetActiveByChamber(project.Chamber);
                foreach (Sensor sensor in sensors)
                {
                    if (!sensor.ApplyCalibration)
                        warnings.Add(String.Format("No calibration applied for sensor '#{0:00} {1}'", sensor.ID + 1, sensor.Description));
                    else
                    {
                        Calibration calibration = new Calibrations().GetLastCreatedBySensorPK(sensor.PK);
                        if (calibration == null)
                            warnings.Add(String.Format("No calibration for sensor '#{0:00} {1}'", sensor.ID + 1, sensor.Description));
                        else if (calibration.Expiry < Time.UTC)
                        {
                            DateTime dt = calibration.Expiry;
                            string msg = string.Format("Calibration for sensor '#{0:00} {1}' expired on {2:0000}/{3:00}/{4:00}", sensor.ID + 1, sensor.Description, dt.Year, dt.Month, dt.Day);
                            warnings.Add(msg);
                        }
                    }
                }
                pboxProjectWarning.Visible = warnings.Count == 0 ? false : true;
            }
            catch (Exception ex)
            {
                warnings.Add("Error: " + ex.Message);
                pboxProjectWarning.Visible = true;
            }
            finally
            {
                lboxProjectNotes.Items.Clear();
                lboxProjectNotes.Items.Add(String.Format("Warnings concerning sensor(s) in chamber {0:00000} {1}", chamber.MIDS, chamber.Description));
                lboxProjectNotes.Items.Add("");
                foreach (String warning in warnings)
                    lboxProjectNotes.Items.Add(warning);
            }

            // Hide conditions. Visible again after first tick of timer
           // lbProjectsSensors.Visible =true;  // was false
            // timerConditions.Interval = Math.Max(5000, chamber.Interval * 500); // At least 5 sec or half the chamber interval  <-- original   
           // timerConditions.Interval = 60000; // interval of 10 sec
           // timerConditions_Tick(null, null);
        }
        


        private void btnStartReset_Click(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
            Project p = SelectedProject;

            if (p == null)
                return;

            DateTime time = dtpStartTime.Value;
            DateTime date = dtpStartDate.Value;
            DateTime start = new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);
            p.Start = Time.LocalToUtc(start);
            try
            {
                new Projects().Modify(p);
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not change project.\n{0}", ex.Message);
                MessageBox.Show(error, "Project details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            dgvProjects_Populate();
            ShowProjectDetails(SelectedProject);
        }

        private void btnStopReset_Click(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
            Project p = SelectedProject;            

            if (p == null)
                return;
            
            DateTime time = dtpStopTime.Value;
            DateTime date = dtpStopDate.Value;
            DateTime stop = new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);
            p.Stop = Time.LocalToUtc(stop);            

            try
            {
                new Projects().Modify(p);
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not change project.\n{0}", ex.Message);
                MessageBox.Show(error, "Project details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            dgvProjects_Populate();
            ShowProjectDetails(SelectedProject);
        }

        private void btnChamberReset_Click(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
            Project p = SelectedProject;

            if (p == null)
                return;

            try
            {
                Chamber c = _ChambersContent[lboxChambersDetails.SelectedIndex];
                p.Chamber = c.PK;
                new Projects().Modify(p);
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not change project.\n{0}", ex.Message);
                MessageBox.Show(error, "Project details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            dgvProjects_Populate();
            ShowProjectDetails(SelectedProject);
        }

        private void menuView_Click(object sender, EventArgs e)
        {
            ShowProjects(ProjectStatus.InProgress);
        }

        private void menuViewFinished_Click(object sender, EventArgs e)
        {
            ShowProjects(ProjectStatus.Finished);
        }

        private void menuViewAll_Click(object sender, EventArgs e)
        {
            ShowProjects(ProjectStatus.None);

            
        }

      


        private void menuNewProject_Click(object sender, EventArgs e)
        {           
            ShowPanelNewProject();
        }

        private void timerProjectDetails_Tick(object sender, EventArgs e)
        {
            Console.WriteLine("REFRESH");

            if ( _ProjectsContent != null)
            {
                try
                {
                    // Update stop date and time
                    dtpStopTime.Value = (SelectedProject.Stop == null) ? Time.Local : Time.UtcToLocal((DateTime)SelectedProject.Stop);
                    dtpStopDate.Value = (SelectedProject.Stop == null) ? Time.Local : Time.UtcToLocal((DateTime)SelectedProject.Stop);
                    btnStopReset.Text = (SelectedProject.Stop == null) ? "Set" : "Change";

                    ShowProjectDetails(SelectedProject);

                    gbProjectDetails.Visible = false;
                }
                catch { }
            }
        }


        private void btnOpenFolderChamber_Click(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
            try
            {
                Chamber chamber = _ChambersContent[lboxChambersDetails.SelectedIndex];               
                if (Directory.Exists(chamber.PathToFolderOnServer))
                    System.Diagnostics.Process.Start(chamber.PathToFolderOnServer);
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not open folder.\n{0}", ex.Message);
                MessageBox.Show(error, "Open folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void btnOpenFolderProject_Click(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();

            try
            {
                if(SelectedProject.ProjectDescription == "Maintenance and calibration")
                {
                    if(SelectedProject.SubProjectDescription == "Service")
                    {
                        string devID = SelectedProject.ProjectID.ToString();
                        devID = devID.Substring(2);
                        System.Diagnostics.Process.Start(String.Format("Z:\\inventory\\{0:00000}\\service", Int32.Parse(devID)));
                    }
                    else
                    {
                        string devID = SelectedProject.ProjectID.ToString();
                        devID = devID.Substring(2);
                        System.Diagnostics.Process.Start(String.Format("Z:\\inventory\\{0:00000}\\calibration", Int32.Parse(devID)));
                    }
                   
                }
                else
                {
                    if (Directory.Exists(SelectedProject.PathToFolderOnServer))
                        System.Diagnostics.Process.Start(SelectedProject.PathToFolderOnServer);
                }
               
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not open folder.\n{0}", ex.Message);
                MessageBox.Show(error, "Open folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }


        private void gbProjectDetails_VisibleChanged(object sender, EventArgs e)
        {
            if (gbProjectDetails.Visible)
            {
                timerProjectDetails.Start(); 
                //timerConditions.Start(); 
            }
            else
            {
                timerProjectDetails.Stop();
                //timerConditions.Stop();
            }
        }


        private void timerUtcClock_Tick(object sender, EventArgs e)
        {
            // Obtain UTC time
            DateTime dt = Time.UTC;
            // Obtain Local time
            DateTime dt_local = Time.UTC.ToLocalTime();
            lblUTCTime.Text = String.Format("Current UTC time is {0:00}:{1:00}, local time is {2:00}:{3:00}.", dt.Hour, dt.Minute, dt_local.Hour, dt_local.Minute);
        }

        public void updateChamberConditions(object sender, EventArgs e)
        {
            
        }
       

        private void pboxProjectWarning_MouseEnter(object sender, EventArgs e)
        {
            pnlNotes.Visible = true;
        }

        private void pboxProjectWarning_MouseLeave(object sender, EventArgs e)
        {
            pnlNotes.Visible = false;   
        }

        public void btnExport_Click(object sender, EventArgs e)
        {
            Project project = SelectedProject;
          
            if (project == null)
                return;

                                  
            DateTime time = dtpStopTime.Value;
            DateTime date = dtpStopDate.Value;

           
            DateTime stop = new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);

                        
            project.Stop = Time.LocalToUtc(stop);
            
            try
            {
                new Projects().Modify(project);
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not change project.\n{0}", ex.Message);
                MessageBox.Show(error, "Project details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
           
          
            dgvProjects_Populate();
            ShowProjectDetails(SelectedProject);

            gbProjectDetails.Visible = false; // Stops timers

            pnlExport.BringToFront();

            gbLinkChambers.Visible = (Control.ModifierKeys == Keys.Shift) ? true : false;

            Chamber chamber = new Chamber();
            try
            {
                chamber = new Chambers().GetByPK(project.Chamber);
                if (chamber == null)
                    throw new Exception("new Chambers().GetByPK(project.PK) returned null");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not retrieve chamber from database!\n\nError: " + ex.Message, "Export project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            if(project.ProjectDescription == "Maintenance and calibration")
            {
                lblExportProject.Text = String.Format("I{0:000000} sub {1:00} step {2:00} in chamber {3:00000}", project.ProjectID, project.SubProject, project.Step, chamber.MIDS);
            }
            else
            {
                lblExportProject.Text = String.Format("P{0:000000} sub {1:00} step {2:00} in chamber {3:00000}", project.ProjectID, project.SubProject, project.Step, chamber.MIDS);
            }
                      
            
            // Initialize export 
            Export.Create(project, chamber);                      

            // Populate dgvLinkChambers (update tracking list _ChambersContent)
            // Do not include the current chamber. 
            int indexOfCurrentChamber = 0;
            List<Chamber> chambers;
            try
            {
                chambers = new Chambers().GetAllActive();
                _ChambersContent.CollectionChanged -= chambers_CollectionChanged;
                _ChambersContent.Clear();
                for(int i=0;i<chambers.Count;i++)
                {
                    if (chambers[i].PK == chamber.PK)
                        indexOfCurrentChamber = i;
                    else
                        _ChambersContent.Add(chambers[i]);
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not retrieve chambers from database!\n\nError: " + ex.Message, "Export project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _ChambersContent.Clear();
                return;
            }
            finally
            {
                // Subscribe again
                _ChambersContent.CollectionChanged += chambers_CollectionChanged;
                chambers_CollectionChanged(null, null); // Fire to update dgv
            }

            // List sensors of current chamber
            dgvLinkChambers_SelectionChanged();

           

            if (MIDSinterface.RowColor(chamber.MIDS) == Color.FromArgb(208, 195, 249) || MIDSinterface.RowColor(chamber.MIDS) == Color.FromArgb(191, 226, 248))     
            { // HAST or Climate chamber :D
                Console.WriteLine("HAST/climate chamber");
                // preselect two Pt100 sensors and RH sensor(s)
                for (int i = 0; i < _SensorsContent.Count; i++)
                {
                    if (_SensorsContent[i].Type == SensorType.Pt100 || _SensorsContent[i].Type == SensorType.PressurecookerRH || _SensorsContent[i].Type == SensorType.PsychrometerRH)
                    {
                        _SensorsContentSelected[i] = true;
                    }
                    else
                    {
                        _SensorsContentSelected[i] = false;
                    }
                }
            }
            else
            { // other type of chamber
                Console.WriteLine("NO HAST/climate chamber");
                // Only preselect two Pt100 sensors
                for (int i = 0; i < _SensorsContent.Count; i++)
                {
                    if (_SensorsContent[i].Type == SensorType.Pt100)
                    {
                        _SensorsContentSelected[i] = true;
                    }
                    else
                    {
                        _SensorsContentSelected[i] = false;
                    }
                }
            }


            // check alle voltage channels. Alle kanalen met bias worden automatisch geselecteerd
            for (int i = 0; i < _SensorsContent.Count; i++)
            {
                if (_SensorsContent[i].Type == SensorType.Voltage)
                {
                    //SqlConnection connection = new SqlConnection("Data Source=MEEU010LAB00003\\FEANOR; Initial Catalog = FEANOR; Persist Security Info=True; User " +
                    //"ID = sa; Password=resam@123resam; connection timeout=15; TrustServerCertificate=True");
                    SqlConnection connection = new SqlConnection("Data Source=tcp:10.126.21.47\\FEANOR,1434; Initial Catalog=FEANOR; User ID=sa; Password=resam@123resam; timeout=15; Persist Security Info=True; TrustServerCertificate=True");

                    try
                    {
                        using (connection)
                        {
                            string query = " ";
                            if(chamber.Humidity == true)
                            {                               
                                query = "SELECT TOP 1 Value FROM Results WHERE SensorPK = @SensorPK AND TimeStamp BETWEEN DATEADD(HOUR, -3, @StopTime) AND DATEADD(HOUR, -2, @StopTime) ORDER BY TimeStamp DESC";
                            }
                            else
                            {                               
                                query = "SELECT TOP 1 Value FROM ResultsOudeHal WHERE SensorPK = @SensorPK AND TimeStamp BETWEEN DATEADD(HOUR, -3, @StopTime) AND DATEADD(HOUR, -2, @StopTime) ORDER BY TimeStamp DESC";
                            }

                            SqlCommand command = new SqlCommand(query, connection);
                            command.Parameters.AddWithValue("@SensorPK", _SensorsContent[i].PK);
                            command.Parameters.AddWithValue("@StopTime", stop);
                                                       
                            connection.Open();

                            object result = command.ExecuteScalar();

                            float resultvalue;

                            if (result != null)
                            {
                                resultvalue = Convert.ToSingle(result); 
                            }
                            else
                            {
                                resultvalue = 0.0f; 
                            }

                            //Console.WriteLine(_SensorsContent[i].PK.ToString() + "  " + resultvalue.ToString());

                            if (resultvalue > 0.1 || resultvalue < -0.1)
                            {
                                _SensorsContentSelected[i] = true;
                            }
                            else
                            {
                                _SensorsContentSelected[i] = false;
                            }                           
                        }                       
                    }
                    catch
                    {
                        
                    }                    
                }
            }





            dgvSensors_SelectionChanged();

            string devID = project.ProjectID.ToString();
            devID = devID.Substring(2);
            Console.WriteLine("DEV ID: ");
            Console.WriteLine(devID);



            // File name to txtb
            if(project.ProjectDescription == "Maintenance and calibration") // INV project
            {
                if (project.SubProjectDescription == "Calibration" || project.SubProjectDescription == "calibration")
                {
                    Console.WriteLine("Calibration");
                    Console.WriteLine(String.Format("Z:\\inventory\\{0:00000}\\calibration\\I{1}.{2} calibration", Int32.Parse(devID), project.ProjectID, project.SubProject));
                    txtbExportPath.Text = String.Format("Z:\\inventory\\{0:00000}\\calibration\\I{1}.{2} calibration", Int32.Parse(devID), project.ProjectID, project.SubProject);
                    txtbFilename.Text = String.Format("I{0}.{1} step {2} calibration.csv",project.ProjectID, project.SubProject, project.Step);
                }
                else if (project.SubProjectDescription == "Service" || project.SubProjectDescription == "service")
                {
                    Console.WriteLine("Service");
                    Console.WriteLine(String.Format("Z:\\inventory\\{0:00000}\\service\\I{1}.{2} service", Int32.Parse(devID), project.ProjectID, project.SubProject));
                    txtbExportPath.Text = String.Format("Z:\\inventory\\{0:00000}\\service\\I{1}.{2} service", Int32.Parse(devID), project.ProjectID, project.SubProject);
                    txtbFilename.Text = String.Format("I{0}.{1} step {2} service.csv", project.ProjectID, project.SubProject, project.Step);
                }
            }            
           else // p project
            {
                txtbExportPath.Text = Export.Project.PathToFolderOnServer;
                txtbFilename.Text = Export.DefaultExportFileName;
            }
        }


        private void dgvLinkChambers_SelectionChanged()
        {
            // Store selected list
            List<Sensor> selectedSensors = new List<Sensor>();
            foreach (DataGridViewRow r in dgvSensors.SelectedRows)
                selectedSensors.Add(_SensorsContent[r.Index]);

            // Get linked chambers. Always include current chamber (from Export)
            // Add sensors of linked chambers
            List<Chamber> linked = new List<Chamber>();
            linked.Add(Export.Chamber);
            for (int i = 0; i < _ChambersContent.Count; i++)
            {
                if (_ChambersContentSelected[i])
                {
                    linked.Add(_ChambersContent[i]);
                    dgvLinkChambers.Rows[i].Selected = true;
                }
                else
                    dgvLinkChambers.Rows[i].Selected = false;
            }

            // Create list of linked sensors
            List<Sensor> linkedSensors = new List<Sensor>();
            try
            {
                foreach (Chamber c in linked)
                {
                    List<Sensor> sensors = new Sensors().GetActiveByChamber(c.PK);
                    foreach (Sensor s in sensors)
                    {
                        if (linked.Count != 1)
                            s.ListDescription = string.Format("{0:00000}.{1:00} {2} ({3})", c.MIDS, s.ID, s.Description, s.Units);
                        else
                            s.ListDescription = string.Format("{0:00} {1} ({2})", s.ID, s.Description, s.Units);
                        linkedSensors.Add(s);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not find linked sensors!\n\n" + ex.Message, "Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Populate _dgvSensorsContent
            try
            {
                _SensorsContent.CollectionChanged -= sensors_CollectionChanged;
                _SensorsContent.Clear();
                foreach (Sensor s in linkedSensors)
                    _SensorsContent.Add(s);
            }
            catch (Exception ex)
            {
                _SensorsContent.Clear();
                MessageBox.Show("Could not find sensors!\n\n" + ex.Message, "Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                // Refresh content
                _SensorsContent.CollectionChanged += sensors_CollectionChanged;
                sensors_CollectionChanged(null, null);
            }

            // Reselect sensors
            List<int> PKs = new List<int>();
            foreach (Sensor s in selectedSensors)
                PKs.Add(s.PK);

            for (int i = 0; i < _SensorsContent.Count; i++)
            {
                if( PKs.Contains(_SensorsContent[i].PK))
                    _SensorsContentSelected[i] = true;
                else
                    _SensorsContentSelected[i] = false;
            }
           
            dgvSensors_SelectionChanged();
        }


        private void dgvSensors_SelectionChanged()
        {
            // Selection acc. _SensorsContentSelected
            for (int i = 0; i < _SensorsContent.Count; i++)
            {
                dgvSensors.Rows[i].Selected = _SensorsContentSelected[i] ? true : false;                
            }                
        }


        // EXPORT AND END TEST!
        private void btnDoExport_Click(object sender, EventArgs e) // EXPORT BUTTON ( indexindex )
        {
                #warning Add the sensors in the primary chamber first. 
            // Add the sensors in the primary chamber first. The first sensor in the list is handled as primary in the export.

            List<Sensor> sensors = new List<Sensor>(); //original
                     
            // Obtain all selected sensors to export (top to bottom)
            for (int i = 0; i < _SensorsContent.Count; i++)
            {
                if((_SensorsContentSelected[i] ? true : false) == true)
                {                   
                    sensors.Add(_SensorsContent[i]);
                }               
            }

            if (sensors.Count == 0)
            {
                MessageBox.Show("No sensors selected!", "Export", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            Export.Sensors = sensors;

            // Construct file and check
            Export.File = txtbExportPath.Text + "\\" + txtbFilename.Text;

            if (!Export.File.ToLower().EndsWith(".csv"))
                Export.File = Export.File + ".csv";

            if (!Directory.Exists(txtbExportPath.Text))
            {
                MessageBox.Show("Folder for export not found!", "Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (File.Exists(Export.File))
            {
                DialogResult dr = MessageBox.Show("File already exists!\n\nDo you want to overwrite?", "Export", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (dr != DialogResult.Yes)
                    return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;
                Export.ToFile();
                MessageBox.Show("Export done!");

                if (cbOpenMeta.Checked == true)
                {
                    try // if .csv file is created succesfully, try to open it in META
                    {
                        string exportFile = txtbExportPath.Text + "\\" + txtbFilename.Text;         // export file path + file name
                        string command = PathToAnalysisTool;                                        // path of META
                        string file = String.Format("\"{0}\"", exportFile);

                        System.Diagnostics.Process.Start(command, file);                            // start META and enter corresponding .csv file
                        

                    }
                    catch (Exception eTDA)
                    {
                        MessageBox.Show(String.Format("Could not start analysis!\n\n{0}", eTDA.Message), "Exporting");
                    }
                }

                ShowProjects(ProjectStatus.InProgress);                                     // show projects which are in progress
                this.Cursor = Cursors.Default;
            }
            catch(Exception ex)
            {     
                MessageBox.Show("Export to file failed!\n\n" +ex.Message, "Export", MessageBoxButtons.OK, MessageBoxIcon.Error); // <-- deze error komt vaak
                return;
            }           
        }

        private void dgvLinkChambers_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int i = e.RowIndex;
            if (i < 0)
                return;

            _ChambersContentSelected[i] = !_ChambersContentSelected[i];
            dgvLinkChambers_SelectionChanged();
        }

        private void dgvSensors_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int i = e.RowIndex;
            if (i < 0)
                return;

            _SensorsContentSelected[i] = !_SensorsContentSelected[i];
            dgvSensors_SelectionChanged();
        }

        private void btnSelectAllSensors_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < _SensorsContentSelected.Length; i++)
                _SensorsContentSelected[i] = true;
            dgvSensors_SelectionChanged();
        }

        private void btnDeSelectAllSensors_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < _SensorsContentSelected.Length; i++)
                _SensorsContentSelected[i] = false;
            dgvSensors_SelectionChanged();
        }

        private void btnExportCancel_Click(object sender, EventArgs e)
        {
            Project project = SelectedProject;

            // reset stop time of project
            project.Stop = null;

            try
            {
                new Projects().Modify(project);
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not change project.\n{0}", ex.Message);
                MessageBox.Show(error, "Project details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ShowProjects(ProjectStatus.InProgress);
            for(int i=0; i<_ProjectsContent.Count;i++)
            {
                if( _ProjectsContent[i].PK == project.PK)
                {
                    dgvProjects.Rows[i].Selected = true;
                    dgvProjects_MouseClick(null, null);
                    break;
                }
            }
        }

        private void dgvProjects_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
            if (e.KeyCode == Keys.Delete)
            {
                MessageBox.Show("Delete a project");
            }            
        }

        private void btnExportPath_Click(object sender, EventArgs e)
        {
            string folder = String.Format("Z:\\projects\\{0}", DateTime.Now.Year);
            if (Directory.Exists(folder))
                FolderBrowserDialog.SelectedPath = folder;
            
            DialogResult dr = FolderBrowserDialog.ShowDialog();
            if (dr == DialogResult.OK)
                txtbExportPath.Text = FolderBrowserDialog.SelectedPath;
        }

        //when inputting project number search for subproject list
        private void txtbNewProjectNumber_TextChanged(object sender, EventArgs e)
        {
            // retreive data inputted by user
            string projectnumb = txtbNewProjectNumber.Text;

            if (cboxInvProject.Checked == true) // INV project
            {
                Console.WriteLine("Inventory Project (I)");

                if (projectnumb.Length == 6)
                {
                    try
                    {

                        txtbNewSubprojectNumber.Focus();

                        List<String> SubProjectList = MIDSinterface.GetINVSubProjectList(int.Parse(projectnumb));

                        if (SubProjectList.Count == 0)
                            return;

                        lbNewSubProjectSelectList.Items.Clear();
                        Int32 i = 1;
                        foreach (String s in SubProjectList)
                        {
                            String item = String.Format("{0:00} {1}", i, s);
                            lbNewSubProjectSelectList.Items.Add(item);
                            i++;
                        }
                        gbNewSubProjectSelectList.Text = "Subprojects in this project";
                        gbNewSubProjectSelectList.Visible = true;
                    }
                    catch
                    {
                    }
                }
            }
            else
            {
                Console.WriteLine("Project (P)");

                if (projectnumb.Length == 6)
                {
                    try
                    {

                        txtbNewSubprojectNumber.Focus();

                        List<String> SubProjectList = MIDSinterface.GetSubProjectList(int.Parse(projectnumb));

                        if (SubProjectList.Count == 0)
                            return;

                        lbNewSubProjectSelectList.Items.Clear();
                        Int32 i = 1;
                        foreach (String s in SubProjectList)
                        {
                            String item = String.Format("{0:00} {1}", i, s);
                            lbNewSubProjectSelectList.Items.Add(item);
                            i++;
                        }
                        gbNewSubProjectSelectList.Text = "Subprojects in this project";
                        gbNewSubProjectSelectList.Visible = true;
                    }
                    catch
                    {
                    }
                }
            }

        }

        // when inputting subproject number search for step list
        private void txtbNewSubprojectNumber_TextChanged(object sender, EventArgs e)
        {
            // retreive data inputted by user
            string projectnumb = txtbNewProjectNumber.Text;
            string subprojectnumb = txtbNewSubprojectNumber.Text;

            if(subprojectnumb.Length > 1)
                txtbNewStepNumber.Focus();

            if (cboxInvProject.Checked == true) // INV project
            {
                Console.WriteLine("Inventory Project (I)");
                if (projectnumb.Length == 6 && subprojectnumb.Length > 0)
                {
                    try
                    {
                        List<String> StepList = MIDSinterface.GetINVStepList(int.Parse(projectnumb), int.Parse(subprojectnumb));

                        try
                        {
                            lbNewStepSelectList.Items.Clear();
                            Int32 i = 1;

                            if (StepList.Count == 0)
                                return;

                            foreach (String step in StepList)
                            {
                                String item = String.Format("{0:00} {1}", i, step);
                                lbNewStepSelectList.Items.Add(item);
                                i++;
                            }
                            gbNewStepSelectList.Text = "Steps in this subproject";
                            gbNewSubProjectSelectList.Visible = false;
                            gbNewStepSelectList.Visible = true;
                        }
                        catch
                        {
                        }
                    }
                    catch
                    {
                    }
                }
            }
            else
            {
                Console.WriteLine("normal project (P)");
                if (projectnumb.Length == 6 && subprojectnumb.Length > 0)
                {
                    try
                    {
                        List<String> StepList = MIDSinterface.GetStepList(int.Parse(projectnumb), int.Parse(subprojectnumb));

                        try
                        {
                            lbNewStepSelectList.Items.Clear();
                            Int32 i = 1;

                            if (StepList.Count == 0)
                                return;

                            foreach (String step in StepList)
                            {
                                String item = String.Format("{0:00} {1}", i, step);
                                lbNewStepSelectList.Items.Add(item);
                                i++;
                            }
                            gbNewStepSelectList.Text = "Steps in this subproject";
                            gbNewSubProjectSelectList.Visible = false;
                            gbNewStepSelectList.Visible = true;
                        }
                        catch
                        {
                        }
                    }
                    catch
                    {
                    }
                }
            }


                         
        }


        private void btnOpenMIDS_Click(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();

            if (SelectedProject.ProjectDescription == "Maintenance and calibration") // INV project
            {
                try
                {
                    Project project = SelectedProject;
                    String target = "https://mids.itiz-me-eu.local/legacy/index.php?section=projects&subsection=subprojects&action=view&action=view&id=";
                    Int32 MIDStableID = MIDSinterface.SubINVProjectMIDSTableID(Convert.ToInt32(project.ProjectID), Convert.ToInt32(project.SubProject));
                    target += MIDStableID.ToString();
                    Console.WriteLine(target);
                    System.Diagnostics.Process.Start(target);
                }
                catch
                {
                }
            }
            else
            {
                try
                {
                    Project project = SelectedProject;
                    String target = "https://mids.itiz-me-eu.local/legacy/index.php?section=projects&subsection=subprojects&action=view&action=view&id=";
                    Int32 MIDStableID = MIDSinterface.SubProjectMIDSTableID(Convert.ToInt32(project.ProjectID), Convert.ToInt32(project.SubProject));
                    target += MIDStableID.ToString();
                    Console.WriteLine(target);
                    System.Diagnostics.Process.Start(target);
                }
                catch
                {
                }
            }
        }

        private void lbNewSubProjectSelectList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get row and return subproject in field NewSubProjectNumber
            // Make pnl invisible
            Int32 Sub = lbNewSubProjectSelectList.SelectedIndex;
            txtbNewSubprojectNumber.Text = String.Format("{0:00}", Sub + 1);
            gbNewSubProjectSelectList.Visible = false;
            gbNewStepSelectList.Visible = true;
        }

        private void lbNewStepSelectList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get row and return subproject in field NewSubProjectNumber
            // Make pnl invisible
            Int32 Step = lbNewStepSelectList.SelectedIndex;
            txtbNewStepNumber.Text = String.Format("{0:00}", Step + 1);
            gbNewStepSelectList.Visible = false;

            btnNewProjectFindMIDS_Click(null, null);
        }
                

        private void btnFindProject_Click(object sender, EventArgs e)
        {    
            try
            {
                if (txtbFindProjectNumber.Text.ToLower().StartsWith("p"))
                    txtbFindProjectNumber.Text = txtbFindProjectNumber.Text.Substring(1);

                Int32 ProjectNumber = 0;
                Int32 SubProjectNumber = 0;
                Int32 StepNumber = 0;
                Int32 Chamber = 0;

                Boolean status = false;

                if (Int32.TryParse(txtbFindProjectNumber.Text, out ProjectNumber))
                    status = true;
                if (Int32.TryParse(txtbFindProjectSub.Text, out SubProjectNumber))
                    status = true;
                if (Int32.TryParse(txtbFindProjectStep.Text, out StepNumber))
                    status = true;
                if (txtbFindCustomer.Text.Length > 0)
                    status = true;
                if (Int32.TryParse(txtbFindChamber.Text, out Chamber))
                    status = true;
                if (txtbFindDescr.Text.Length > 0)
                    status = true;

                if (!status)
                {
                    MessageBox.Show("Inputformat incorrect!", "Find project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                List<Project> projectList = new Projects().GetAll();
                List<int> indexToRemove = new List<int>();

                // If ProjectNumber != 0 filter out non-matching
                if (ProjectNumber > 0)
                {
                    for (int i = 0; i < projectList.Count; i++)
                    {
                        if (!projectList[i].ProjectID.ToString().EndsWith(ProjectNumber.ToString()))
                            indexToRemove.Add(i);
                    }
                }

                // If SubProjectNumber != 0 filter out non-matching
                if (SubProjectNumber > 0)
                {
                    for (int i = 0; i < projectList.Count; i++)
                    {
                        if (!projectList[i].SubProject.ToString().EndsWith(SubProjectNumber.ToString()))
                            indexToRemove.Add(i);
                    }
                }

                // If StepNumber != 0 filter out non-matching
                if (StepNumber > 0)
                {
                    for (int i = 0; i < projectList.Count; i++)
                    {
                        if (!projectList[i].Step.ToString().EndsWith(StepNumber.ToString()))
                            indexToRemove.Add(i);
                    }
                }

                // If Customer is not empty filter out non-matching
                if (txtbFindCustomer.Text.Length > 0)
                {                   
                    String needle = txtbFindCustomer.Text.ToLower().Trim();
                    bool keep;

                    for (int i = 0; i < projectList.Count; i++)
                    {
                        keep = false;

                        if (projectList[i].Customer.ToLower().Contains(needle))
                            keep = true;


                        if (!keep)
                            indexToRemove.Add(i);
                    }

                }



                // If description is not empty filter out non-matching
                if (txtbFindDescr.Text.Length > 0)
                {
                    String needle = txtbFindDescr.Text.ToLower().Trim();
                    bool keep;

                    for (int i = 0; i < projectList.Count; i++)
                    {
                        keep = false;

                        if (projectList[i].ProjectDescription.ToLower().Contains(needle))
                            keep = true;

                        if (projectList[i].SubProjectDescription.ToLower().Contains(needle))
                            keep = true;

                        if (projectList[i].StepDescription.ToLower().Contains(needle))
                            keep = true;

                        if (!keep)
                            indexToRemove.Add(i);
                    }
                }
                                

                // If Chamber != 0 filter out non-matching
                if (Chamber > 0)
                {
                    // Get chamber_PK by given MIDS ID
                    int Chamber_PK = 0;
                    List<Chamber> chamberList = new Chambers().GetAll();

                    foreach (Chamber cc in chamberList)
                        if (cc.MIDS == Chamber)
                            Chamber_PK = cc.PK; // was c.Chamber_PK;


                    if (Chamber_PK > 0)
                    {
                        for (int i = 0; i < projectList.Count; i++)
                        {
                            if (projectList[i].Chamber != Chamber_PK)
                                indexToRemove.Add(i);
                        }
                    }
                }


                if (_ProjectsContent == null)
                {
                    gbProjectList.Text = "Projects (0)";
                    dgvProjects.Rows.Clear();
                    return;
                }
                if (_ProjectsContent.Count == 0)
                {
                    gbProjectList.Text = "Projects (0)";
                    dgvProjects.Rows.Clear();
                    return;
                }

                // Remove enough rows or add missing ones
                while (dgvProjects.Rows.Count > _ProjectsContent.Count)
                    dgvProjects.Rows.RemoveAt(0);
                if (dgvProjects.Rows.Count < _ProjectsContent.Count)
                    dgvProjects.Rows.Add(_ProjectsContent.Count - dgvProjects.Rows.Count);


                List<Project> projectListItemList = new List<Project>();

                dgvProjects.Rows.Clear();

                for (int i = 0; i < projectList.Count; i++) // projectList --> ALL projects
                {
                    if (!indexToRemove.Contains(i))
                    { 
                        projectListItemList.Add(projectList[i]);                        
                        Console.WriteLine(projectList[i].ProjectID);                      
                    }
                }

                _ProjectsContent.CollectionChanged -= projects_CollectionChanged; // Unsubscribe to prevent reoccuring firing
                _ProjectsContent.Clear();
                foreach (Project p in projectListItemList)
                    _ProjectsContent.Add(p);
                      
                // Subscribe again and fire
                _ProjectsContent.CollectionChanged += projects_CollectionChanged;
                projects_CollectionChanged(null, null);

               
                dgvProjects.ClearSelection();

                pnlViewProjects.Visible = true;
                gbProjectList.Text = String.Format("Projects found ({0})", projectListItemList.Count);
                pnlFindProject.Visible = false;
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not find project.\n\n{0}", ex.Message);
                MessageBox.Show(error, "Find project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                txtbFindCustomer.Clear();
                txtbFindChamber.Clear();
                txtbFindDescr.Clear();
            }
            
        }

        private void btnStopReReset_Click(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
            Project p = SelectedProject;

            p.Stop = null;

            try
            {
                new Projects().Modify(p);
            }
            catch (Exception ex)
            {
                string error = String.Format("Could not change project.\n{0}", ex.Message);
                MessageBox.Show(error, "Project details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            dgvProjects_Populate();
            ShowProjectDetails(SelectedProject);
            ShowProjects(ProjectStatus.InProgress);            
        }

        private void btnCancelNewProject_Click(object sender, EventArgs e)
        {
            ShowProjects(ProjectStatus.InProgress);
        }

        private void sensorConditions_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void btnNodeStatus_Click(object sender, EventArgs e)
        {
          
            timerProjectDetails.Stop();
            timerProjectDetails.Start();

            Project project = SelectedProject;            
            Chamber chamber;            
                        
            int ChamberPK = project.Chamber;
           
            chamber = new Chambers().GetByPK(ChamberPK);            

            String UrlString = "http://" + chamber.Network + ":8080/status";

            // voor niet CMS2 PC's kan de NodeStatus niet direct opgehaald worden (omweg door de Nodestatus html op te slaan op Z:)
            if (CMS2PC == false)
            {
                try
                {
                    string fileName = $"Node_{chamber.MIDS}_status.html";
                    string filePath = Path.Combine("Z:\\projects\\2020\\P201339\\sub1\\4. Software\\8. Nodestatus\\", fileName);

                    if (File.Exists(filePath))
                    {
                        Process.Start(new ProcessStartInfo
                        {
                            FileName = filePath,
                            UseShellExecute = true
                        });                        
                    }                   
                }
                catch { }  
                return; 
            }

            System.Diagnostics.Process.Start(UrlString);

            try
            {
                using (WebClient client = new WebClient())
                {
                    string dta = client.DownloadString(UrlString);          // send status HTTP request to cms node
                }    
            }
            catch
            {
                Console.WriteLine("Status request error!");
                System.Windows.Forms.MessageBox.Show("No response from CMS-2 node");
            }        

        }

        //  EXPORT WITHOUT ENDING TEST!!!
        private void btnExpNoDate_Click(object sender, EventArgs e)
        {
#warning Add the sensors in the primary chamber first. 
            // Add the sensors in the primary chamber first. The first sensor in the list is handled as primary in the export.

            List<Sensor> sensors = new List<Sensor>(); //original

            // Obtain all selected sensors to export (top to bottom)
            for (int i = 0; i < _SensorsContent.Count; i++)
            {
                if ((_SensorsContentSelected[i] ? true : false) == true)
                {
                    sensors.Add(_SensorsContent[i]);
                }
            }

            if (sensors.Count == 0)
            {
                MessageBox.Show("No sensors selected!", "Export", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            Export.Sensors = sensors;

            // Construct file and check
            Export.File = txtbExportPath.Text + "\\" + txtbFilename.Text;

            if (!Export.File.ToLower().EndsWith(".csv"))
                Export.File = Export.File + ".csv";

            if (!Directory.Exists(txtbExportPath.Text))
            {
                MessageBox.Show("Folder for export not found!", "Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (File.Exists(Export.File))
            {
                DialogResult dr = MessageBox.Show("File already exists!\n\nDo you want to overwrite?", "Export", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (dr != DialogResult.Yes)
                    return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;
               
                Export.ToFile();
                MessageBox.Show("Export done!");

                // reset stop date!!                
                Export.Project.Stop = null;

                try
                {
                    new Projects().Modify(Export.Project);
                }
                catch (Exception ex)
                {
                    string error = String.Format("Could not change project.\n{0}", ex.Message);
                    MessageBox.Show(error, "Project details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                dgvProjects_Populate();
                ShowProjectDetails(SelectedProject);
                ShowProjects(ProjectStatus.InProgress);
              
                if(cbOpenMeta.Checked==true)
                {
                    try // if .csv file is created succesfully, try to open it in META
                    {                        
                        string exportFile = txtbExportPath.Text + "\\" + txtbFilename.Text;         // export file path + file name                       
                        string command = PathToAnalysisTool;                                        // path of META                       
                        string file = String.Format("\"{0}\"", exportFile);                      
                        System.Diagnostics.Process.Start(command, file);                            // start META and enter corresponding .csv file     
                    }
                    catch (Exception eTDA)
                    {
                        MessageBox.Show(String.Format("Could not start analysis!\n\n{0}", eTDA.Message), "Exporting");
                    }
                }
                ShowProjects(ProjectStatus.InProgress);                                     // show projects which are in progress
                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Export to file failed!\n\n" + ex.Message, "Export", MessageBoxButtons.OK, MessageBoxIcon.Error); // <-- deze error komt vaak
                return;
            }
        }

        private void cboxInvProject_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void dgvProjects_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void lboxChambersDetails_SelectedIndexChanged(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
        }

        private void dtpStartDate_ValueChanged(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
        }

        private void dtpStartTime_ValueChanged(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
        }

        private void dtpStopDate_ValueChanged(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
        }

        private void dtpStopTime_ValueChanged(object sender, EventArgs e)
        {
            timerProjectDetails.Stop();
            timerProjectDetails.Start();
        }

        private void txtbNewStepNumber_TextChanged(object sender, EventArgs e)
        {
            if(txtbNewStepNumber.Text != "")
                btnNewProjectFindMIDS.PerformClick();
        }

        private void dgvSensors_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void lboxChambersNew_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void menuViewFind_Click(object sender, EventArgs e)
        {
            pnlFindProject.Visible = true;
            txtbFindProjectNumber.Text = "";
            txtbFindProjectSub.Text = "";
            txtbFindProjectStep.Text = "";
        }

        private void btnFindCancel_Click(object sender, EventArgs e)
        {
            pnlFindProject.Visible = false;
        }

        private void txtbFindProjectSub_TextChanged(object sender, EventArgs e)
        {

        }

        private void finishedLastMonthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowProjects(ProjectStatus.FinishedLastMonth);
        }

        private void finishedLastWeekToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowProjects(ProjectStatus.FinishedLastWeek);
        }

        private void gbProjectList_Enter(object sender, EventArgs e)
        {

        }

        private void btnChamberSensors_Click(object sender, EventArgs e)
        {
            lbChamberConditions.Items.Clear();

            Project project = SelectedProject;

            Chamber chamber = new Chamber();
            try
            {
                chamber = new Chambers().GetByPK(project.Chamber);
                if (chamber == null)
                    throw new Exception("new Chambers().GetByPK(project.PK) returned null");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not retrieve chamber from database!\n\nError: " + ex.Message, "Export project", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            List<Sensor> sensors;
            try
            {
                sensors = new Sensors().GetByChamber(project.Chamber);               
            }
            catch (Exception ex)
            {
                sensors = new List<Sensor>(); // Zorg ervoor dat sensors altijd geïnitialiseerd is
            }


            for (int i = 0; i < sensors.Count; i++)
            {
                SqlConnection connection = new SqlConnection("Data Source=tcp:10.126.21.47\\FEANOR,1434; Initial Catalog=FEANOR; User ID=sa; Password=resam@123resam; timeout=15; Persist Security Info=True; TrustServerCertificate=True");

                    try
                {
                        using (connection)
                        {
                            string query = " ";
                            if (chamber.Humidity == true)
                            {
                                query = "SELECT TOP 1 Value FROM Results WHERE SensorPK = @SensorPK AND TimeStamp >= DATEADD(MINUTE, -10, GETUTCDATE())  ORDER BY TimeStamp DESC ";
                            }
                            else
                            {
                                query = "SELECT TOP 1 Value FROM ResultsOudeHal WHERE SensorPK = @SensorPK  AND TimeStamp >= DATEADD(MINUTE, -10, GETUTCDATE())  ORDER BY TimeStamp DESC";
                            }

                            SqlCommand command = new SqlCommand(query, connection);
                        command.Parameters.AddWithValue("@SensorPK", sensors[i].PK);
                           
                            connection.Open();

                            object result = command.ExecuteScalar();

                            float resultvalue;

                            if (result != null)
                            {
                                resultvalue = Convert.ToSingle(result);
                            }
                            else
                            {
                                resultvalue = 0.0f;
                            }

                            Console.WriteLine(sensors[i].PK.ToString() + "  " + resultvalue.ToString() + "  " + sensors[i].Type.ToString());
                        
                        if (sensors[i].Type == SensorType.Pt100) 
                        {
                            lbChamberConditions.Items.Add("ch" + i.ToString() + " :\t" + resultvalue.ToString() + " °C"); 
                        }
                        else if (sensors[i].Type == SensorType.Voltage) 
                        {
                            if (resultvalue > 0.1 ||resultvalue<-0.1)
                            {
                                lbChamberConditions.Items.Add("ch" + i.ToString() + " :\t" + resultvalue.ToString() + " V");
                            }                           
                        }
                        else
                        {
                            if (resultvalue != 0.0) { lbChamberConditions.Items.Add("ch" + i.ToString() + " :\t" + resultvalue.ToString() + " % RH"); }
                        }
                    }
                    }
                    catch
                    {

                    }
               
            }


        }
    }

    
}
