using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Maser.Feanor.Model;
using System.Drawing;
using MySqlConnector;

namespace Maser.Feanor.MIDSInterface
{
    public static partial class MIDSinterface // was public static partial class MIDSinterface
    {
        #region Server parameters
        // Server acces parameters
        const string UserID = "mids_userquery";
        const string Password = "23uRUVfq6dXXHMWN";
        const string Catalog = "mids_maser";
        const string Server = "meeu001sqvp007.itiz-me-eu.local"; // was enterprise.maser.nl

        // Help variables, not accessible
        private static Int32 _DB_project_id;
        private static Int32 _DB_subproject_id;
        private static Int32 _DB_step_id;
        private static Int32 _DB_customer_id;
        private static Int32 _DB_chamber_id;
        #endregion Server parameters

        // Table names
        const string TProjects = "projects";
        const string TSubprojects = "subprojecten";
        const string TRelations = "relations";
        const string TSubproject_SubprojectNumber = "subprojecten_subnumber";
        const string TSubprojectsteps = "subprojectsteps";
        const string TChambers = "inventory";
        const string TStepInventory = "subproject_step_inventory_list";
        // Field names
        const string FProjectsName = "name";
        const string FRelationsName = "relations.name";
        const string FProjectsNumber = "number";
        const string FPRojectsCustomer_id = "customer_id";
        const string FSubProjectsName = "naam";
        const string FSubProjectsProject_id = "project_id";
        const string FSubproject_SubprojectnumberSubproject_id = "subproject_id";
        const string FSubproject_SubprojectnumberSubnumber = "subnumber";
        const string FSubprojectstepsName = "beschrijving";
        const string FSubprojectstepsNumber = "volgorde";
        const string FSubprojectStepID = "subprojectsteps.id";



        // Get project description, customer, subproject descrption, step info and goods
        public static Project GetProject(Int32 project, Int32 subproject, Int32 step)
        {
            Project proj = new Project();

            proj.ProjectID = project;       // MIDSProject --> ProjectID
            proj.SubProject = subproject;   // MIDSSubProject --> SubProject
            proj.Step = step;               // MIDSStep --> Step
            
            // MIDSProjectDescription --> ProjectDescription
            // MIDSCustomerDiscription --> Customer

            String query;
            MySqlCommand cmd;
            MySqlConnection Connection = null;

            #region Project description & Customer description
            try
            {
                query = String.Format("SELECT projects.id as pid, projects.name as pname, relations.id as rid, relations.name as rname FROM projects join relations on relations.id = customer_id WHERE number='P{0:000000}'", proj.ProjectID);

                Connection = GetConnection();
                cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();

                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {

                    while (reader.Read())
                    {
                       //proj.ProjectDescription = reader["pname"].ToString().Replace(Environment.NewLine, " | "); // <-- original
                        proj.ProjectDescription = reader["pname"].ToString().Replace("&amp;", "&");
                        proj.Customer = reader["rname"].ToString().Replace(Environment.NewLine, " | ");
                        _DB_project_id = Int32.Parse(reader["pid"].ToString());
                        _DB_customer_id = Int32.Parse(reader["rid"].ToString());                        
                    }
                }
                else
                {
                    proj.ProjectDescription = "n/a";
                    proj.Customer = "n/a";
                }

                // Call Close when done reading.
                reader.Close();
            }
            catch (Exception e)
            {
                proj.ProjectDescription = "Exception: " + e.Message;
                proj.Customer = "Exception: " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
            #endregion Project description & Customer description
         
            #region Subproject description
            try
            {
                query = "SELECT naam, subprojecten.id as id FROM subprojecten JOIN projects ON projects.id=subprojecten.project_id JOIN subprojecten_subnumber ON ";
                query += "subprojecten.id=subprojecten_subnumber.subproject_id WHERE projects.number=";
                query += String.Format("'P{0:000000}' ", proj.ProjectID);
                query += "AND subprojecten_subnumber.subnumber=" + proj.SubProject.ToString();

                Connection = GetConnection();
                cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        //proj.SubProjectDescription = reader["naam"].ToString().Replace(Environment.NewLine, " | ");
                        proj.SubProjectDescription = reader["naam"].ToString().Replace("&amp;", "&");
                        _DB_subproject_id = Int32.Parse(reader["id"].ToString());
                    }
                else
                    proj.SubProjectDescription = "n/a";
                reader.Close();


            }
            catch (Exception e)
            {
                proj.SubProjectDescription = "Exception : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
            #endregion Subproject description


            #region Step info
            try
            {
                query = "SELECT id, beschrijving, s_in, s_out, s_fail, use_tested_fields FROM `subprojectsteps` WHERE subproject_id = " + _DB_subproject_id.ToString();
                query += " ORDER BY subprojectsteps.volgorde ASC LIMIT " + (proj.Step - 1).ToString() + ",1";
                Connection = GetConnection();
                cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        _DB_step_id = Int32.Parse(reader["id"].ToString());

                        //string descr = reader["beschrijving"].ToString().Replace(Environment.NewLine, " | ");
                        string descr = reader["beschrijving"].ToString().Replace("&amp;", "&");
                        descr = descr.Replace(System.Environment.NewLine, " ");
                        proj.StepDescription = descr;

                        /*
                        if (Int32.Parse(reader["use_tested_fields"].ToString()) > 0)
                        {
                            int tested = Int32.Parse(reader["s_in"].ToString());
                            int passed = Int32.Parse(reader["s_out"].ToString());
                            int failed = Int32.Parse(reader["s_fail"].ToString());
                           // proj.UseTPF = true;
                           // proj.TestPassFail = new Int32[3] { tested, passed, failed };
                        }
                        */

                        // START & STOP!

                    }
                else
                    proj.StepDescription = "n/a";
                reader.Close();
            }
            catch (Exception e)
            {
                proj.StepDescription = "Exception : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
            #endregion Step info


            #region Goods
            /*
            List<Goods> goods = new List<Goods>();

            try
            {
                query = "SELECT * FROM shipping_goods_subprojects JOIN shipping_goods on shipping_goods.id =  shipping_goods_subprojects.goods_id WHERE shipping_goods_subprojects.subproject_id = " + _DB_subproject_id.ToString();
                Connection = GetConnection();
                cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        String description = reader["description"].ToString();
                        int amount = Int32.Parse(reader["amount"].ToString());
                        String typecode = reader["typecode"].ToString();
                        String datecode = reader["datecode"].ToString();
                        String lotcode = reader["lotcode"].ToString();
                        String manufacturer = reader["manufacturer"].ToString();
                        String serialnr = reader["serialnr"].ToString();
                        String packagetype = reader["packagetype"].ToString();
                        String customer_reference = reader["customer_reference"].ToString();
                        Goods g = new Goods(description, amount, typecode, datecode, lotcode, manufacturer, serialnr, packagetype, customer_reference);
                        goods.Add(g);
                    }
                    proj.Goods = goods;
                }
                else
                {
                    proj.Goods = new List<Goods>();
                }
                reader.Close();
            }
            catch
            {
                proj.Goods = new List<Goods>();
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
            */
            #endregion Goods


            return proj;
        }

       

        public static (double temperature, double humidity) GetTemp()
        {
            string query;
            MySqlCommand cmd;
            MySqlConnection connection = null;

            double temperature = 0.0;
            double humidity = 0.0;

            try
            {
                // Query om temperatuur en luchtvochtigheid op te halen
                query = "SELECT temperature, humidity FROM `sensor_data` WHERE ip='192.168.1.166' ORDER BY timestamp DESC LIMIT 1";

                // Verbinding maken
                connection = GetConnection();
                cmd = new MySqlCommand(query, connection);
                connection.Open();

                // Voer de query uit
                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        // Haal de temperatuur en luchtvochtigheid op
                        temperature = reader.IsDBNull(0) ? 0.0 : reader.GetDouble(0);
                        humidity = reader.IsDBNull(1) ? 0.0 : reader.GetDouble(1);
                    }
                }
                else
                {
                    // Geen gegevens gevonden, geef 0.0 terug
                    Console.WriteLine("Geen gegevens gevonden voor de opgegeven IP.");
                }

                // Sluit de reader na gebruik
                reader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Fout bij het ophalen van data: " + e.Message);
            }
            finally
            {
                // Zorg ervoor dat de verbinding altijd wordt gesloten
                if (connection != null)
                    connection.Close();
            }

            // Retourneer de temperatuur en luchtvochtigheid als tuple
            return (temperature, humidity);
        }



        // Get chamber number
        public static Chamber GetChamber(Int32 project, Int32 subproject, Int32 step)
        {
            Chamber chamber = new Chamber();

            // Fill in _DB_step_id
            Project proj = GetProject(project, subproject, step);

            String query;
            MySqlCommand cmd;
            MySqlConnection Connection = null;

            try
            {
                query = "SELECT inventory.id as iid, nummer, beschrijving FROM inventory_step_usage JOIN inventory ON inventory.id = inventory_step_usage.inventory_id WHERE step_id =" + _DB_step_id.ToString();

                Connection = GetConnection();
                cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        _DB_chamber_id = Int32.Parse(reader["iid"].ToString());
                        chamber.MIDS = Int32.Parse(reader["nummer"].ToString());
                        chamber.Description = reader["beschrijving"].ToString().Replace(Environment.NewLine, " | ");
                    }
                else
                {
                    chamber.MIDS = 0;
                    chamber.Description = "n/a";
                }
                reader.Close();
            }
            catch (Exception e)
            {
                chamber.MIDS = 0;
                chamber.Description = "Exception : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
            return chamber;
        }

        // Get chamber description
        public static Chamber GetChamber(Int32 MIDS)
        {
            Chamber chamber = new Chamber();

            String query;
            MySqlCommand cmd;
            MySqlConnection Connection = null;

            try
            {
                query = "SELECT id, nummer, beschrijving  FROM `inventory` WHERE nummer = " + MIDS.ToString();

                Connection = GetConnection();
                cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        _DB_chamber_id = Int32.Parse(reader["id"].ToString());
                        chamber.MIDS = Int32.Parse(reader["nummer"].ToString());
                        chamber.Description = reader["beschrijving"].ToString();
                    }
                else
                {
                    chamber.MIDS = 0;
                    chamber.Description = "n/a";
                }
                reader.Close();
            }
            catch (Exception e)
            {
                chamber.MIDS = 0;
                chamber.Description = "Exception : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
            return chamber;
        }

        // Get planned chamber number + description
        public static Chamber GetPlannedChamber(Int32 project, Int32 subproject, Int32 step)
        {
            Chamber chamber = new Chamber();

            // Fill in _DB_step_id
            Project proj = GetProject(project, subproject, step);

            String query;
            MySqlCommand cmd;
            MySqlConnection Connection = null;

            try
            {
                query = "SELECT inventory.id as iid, nummer, beschrijving FROM inventory_step_planning JOIN inventory ON inventory.id = inventory_step_planning.inventory_id WHERE step_id =" + _DB_step_id.ToString();

                Connection = GetConnection();
                cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                    while (reader.Read())
                    {
                        _DB_chamber_id = Int32.Parse(reader["iid"].ToString());
                        chamber.MIDS = Int32.Parse(reader["nummer"].ToString());
                        chamber.Description = reader["beschrijving"].ToString();
                    }
                else
                {
                    chamber.MIDS = 0;
                    chamber.Description = "n/a";
                }
                reader.Close();
            }
            catch (Exception e)
            {
                chamber.MIDS = 0;
                chamber.Description = "Exception : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
            return chamber;
        }

        
        private static MySqlConnection GetConnection()
        {
            try
            {
                string ConnectionString = String.Format("DataSource={0};Persist Security Info=False;Initial Catalog={1};Connect Timeout=30;Username={2}; Password={3};", Server, Catalog, UserID, Password);
                MySqlConnection myConnection = new MySqlConnection();
                myConnection.ConnectionString = ConnectionString;
                return myConnection;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        

        public static Int64 GetNumOfSubProjects(Int32 ProjectNumber)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    COUNT(naam)
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //WHERE 
                //    projects.number='P080799' 

                             

                String query = String.Format(
                    "SELECT " +
                    "COUNT({0})" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " WHERE " +
                    "{2}.{6}='P{7:000000}'",
                    FSubProjectsName,
                    TSubprojects,
                    TProjects,
                    FSubProjectsProject_id,
                    TSubproject_SubprojectNumber,
                    FSubproject_SubprojectnumberSubproject_id,
                    FProjectsNumber,
                    ProjectNumber,
                    FSubproject_SubprojectnumberSubnumber
                    //SubProjectNumber
                );
                Connection = GetConnection();
                Console.WriteLine(Connection.ConnectionString.ToString());
                MySqlCommand cmd = new MySqlCommand(query);
                Console.WriteLine("query " + query.ToString());               
                cmd.Connection = Connection;
                Console.WriteLine(Connection.ConnectionString.ToString());
                
                Connection.Open();
                Int64 result = (Int64)cmd.ExecuteScalar();



                Console.WriteLine("result " + result.ToString());
                return result;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static List<String> GetSubProjectList(Int32 ProjectNumber)
        {
            List<String> SubProjectNamesList = new List<string>();
            Int64 NumOfSubs = GetNumOfSubProjects(ProjectNumber);            
            for (int i = 1; i <= NumOfSubs; i++)
            {
              SubProjectNamesList.Add(GetSubProjectName(ProjectNumber, i));                
            }
            return SubProjectNamesList;
        }

        public static Int64 GetNumOfSteps(Int32 ProjectNumber, Int32 SubProjectNumber)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    beschrijving
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //JOIN
                //    subprojectsteps
                //ON
                //    subprojectsteps.subproject_id=subprojecten.id
                //WHERE 
                //    projects.number='P080591' 
                //AND
                //    subprojecten_subnumber.subnumber='3'
                //ORDER BY subprojectsteps.volgorde ASC
                //LIMIT [stepnumber],1

                String query = String.Format(
                    "SELECT " +
                    "COUNT({0})" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " JOIN " +
                    " {10} " +
                    " ON " +
                    "{10}.{5}={1}.id" +
                    " WHERE " +
                    "{2}.{6}='P{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'" +
                    " ORDER BY {10}.{11} ASC ",
                    FSubprojectstepsName,                       //0
                    TSubprojects,                               //1
                    TProjects,                                  //2
                    FSubProjectsProject_id,                     //3
                    TSubproject_SubprojectNumber,               //4
                    FSubproject_SubprojectnumberSubproject_id,  //5
                    FProjectsNumber,                            //6
                    ProjectNumber,                         //7
                    FSubproject_SubprojectnumberSubnumber,      //8
                    SubProjectNumber,                      //9
                    TSubprojectsteps,                           //10
                    FSubprojectstepsNumber                      //11
                );

                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
                
                cmd.Connection = Connection;
                Connection.Open();
                Int64 result = (Int64)cmd.ExecuteScalar();
                return result;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static List<String> GetStepList(Int32 ProjectNumber, Int32 SubProjectNumber)
        {
            List<String> StepList = new List<string>();
            Int64 NumOfSteps = GetNumOfSteps( ProjectNumber,  SubProjectNumber);
            for (int i = 1; i <= NumOfSteps; i++)
            {
              StepList.Add(GetStepName(ProjectNumber,SubProjectNumber, i));                
            }
            return StepList;
        }

        public static string GetSubProjectName(Int32 ProjectNumber, Int64 N)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    naam
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //WHERE 
                //    projects.number='P080799' 
                //AND
                //    subprojecten_subnumber.subnumber='2'

                String query = String.Format(
                    "SELECT " +
                    "{0}" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " WHERE " +
                    "{2}.{6}='P{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'",
                    FSubProjectsName,
                    TSubprojects,
                    TProjects,
                    FSubProjectsProject_id,
                    TSubproject_SubprojectNumber,
                    FSubproject_SubprojectnumberSubproject_id,
                    FProjectsNumber,
                    ProjectNumber,
                    FSubproject_SubprojectnumberSubnumber,
                    N
                );
                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
                
                cmd.Connection = Connection;
                Connection.Open();
                string result = (string)cmd.ExecuteScalar();
                if (result == null)
                    return "n/a";
                else
                    return result;
            }
            catch (Exception e)
            {
                return "ERROR : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static string GetStepName(Int32 ProjectNumber, Int32 SubProjectNumber, Int64 N)
        // Stepname of step N in current project and subproject
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    beschrijving
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //JOIN
                //    subprojectsteps
                //ON
                //    subprojectsteps.subproject_id=subprojecten.id
                //WHERE 
                //    projects.number='P080591' 
                //AND
                //    subprojecten_subnumber.subnumber='3'
                //ORDER BY subprojectsteps.volgorde ASC
                //LIMIT [stepnumber],1

                String query = String.Format(
                    "SELECT " +
                    "{0}" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " JOIN " +
                    " {10} " +
                    " ON " +
                    "{10}.{5}={1}.id" +
                    " WHERE " +
                    "{2}.{6}='P{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'" +
                    " ORDER BY {10}.{11} ASC " +
                    " LIMIT {12}, 1 ",
                    FSubprojectstepsName,                       //0
                    TSubprojects,                               //1
                    TProjects,                                  //2
                    FSubProjectsProject_id,                     //3
                    TSubproject_SubprojectNumber,               //4
                    FSubproject_SubprojectnumberSubproject_id,  //5
                    FProjectsNumber,                            //6
                    ProjectNumber,                         //7
                    FSubproject_SubprojectnumberSubnumber,      //8
                    SubProjectNumber,                      //9
                    TSubprojectsteps,                           //10
                    FSubprojectstepsNumber,                     //11
                    N - 1                           //12
                );

                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
               
                cmd.Connection = Connection;
                Connection.Open();
                string result = (string)cmd.ExecuteScalar();
                result = result.Replace("\t", " - ").Replace("\r", " - ").Replace("\n", " - ");
                if (result == null)
                    return "n/a";
                else
                    return result;
            }
            catch (Exception e)
            {
                return "ERROR : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }



        public static Int64 GetINVNumOfSubProjects(Int32 ProjectNumber)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    COUNT(naam)
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //WHERE 
                //    projects.number='P080799' 



                String query = String.Format(
                    "SELECT " +
                    "COUNT({0})" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " WHERE " +
                    "{2}.{6}='I{7:000000}'",
                    FSubProjectsName,
                    TSubprojects,
                    TProjects,
                    FSubProjectsProject_id,
                    TSubproject_SubprojectNumber,
                    FSubproject_SubprojectnumberSubproject_id,
                    FProjectsNumber,
                    ProjectNumber,
                    FSubproject_SubprojectnumberSubnumber
                //SubProjectNumber
                );
                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
                Console.WriteLine("query " + query.ToString());
                
                cmd.Connection = Connection;
                Connection.Open();
                Int64 result = (Int64)cmd.ExecuteScalar();
                Console.WriteLine("result "+result.ToString());
                return result;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static List<String> GetINVSubProjectList(Int32 ProjectNumber)
        {
            List<String> SubProjectNamesList = new List<string>();
            Int64 NumOfSubs = GetINVNumOfSubProjects(ProjectNumber);
            for (int i = 1; i <= NumOfSubs; i++)
            {
                SubProjectNamesList.Add(GetINVSubProjectName(ProjectNumber, i));
            }
            return SubProjectNamesList;
        }
        public static string GetINVSubProjectName(Int32 ProjectNumber, Int64 N)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    naam
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //WHERE 
                //    projects.number='P080799' 
                //AND
                //    subprojecten_subnumber.subnumber='2'

                String query = String.Format(
                    "SELECT " +
                    "{0}" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " WHERE " +
                    "{2}.{6}='I{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'",
                    FSubProjectsName,
                    TSubprojects,
                    TProjects,
                    FSubProjectsProject_id,
                    TSubproject_SubprojectNumber,
                    FSubproject_SubprojectnumberSubproject_id,
                    FProjectsNumber,
                    ProjectNumber,
                    FSubproject_SubprojectnumberSubnumber,
                    N
                );
                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
               
                cmd.Connection = Connection;
                Connection.Open();
                string result = (string)cmd.ExecuteScalar();
                if (result == null)
                    return "n/a";
                else
                    return result;
            }
            catch (Exception e)
            {
                return "ERROR : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static Int64 GetINVNumOfSteps(Int32 ProjectNumber, Int32 SubProjectNumber)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    beschrijving
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //JOIN
                //    subprojectsteps
                //ON
                //    subprojectsteps.subproject_id=subprojecten.id
                //WHERE 
                //    projects.number='P080591' 
                //AND
                //    subprojecten_subnumber.subnumber='3'
                //ORDER BY subprojectsteps.volgorde ASC
                //LIMIT [stepnumber],1

                String query = String.Format(
                    "SELECT " +
                    "COUNT({0})" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " JOIN " +
                    " {10} " +
                    " ON " +
                    "{10}.{5}={1}.id" +
                    " WHERE " +
                    "{2}.{6}='I{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'" +
                    " ORDER BY {10}.{11} ASC ",
                    FSubprojectstepsName,                       //0
                    TSubprojects,                               //1
                    TProjects,                                  //2
                    FSubProjectsProject_id,                     //3
                    TSubproject_SubprojectNumber,               //4
                    FSubproject_SubprojectnumberSubproject_id,  //5
                    FProjectsNumber,                            //6
                    ProjectNumber,                         //7
                    FSubproject_SubprojectnumberSubnumber,      //8
                    SubProjectNumber,                      //9
                    TSubprojectsteps,                           //10
                    FSubprojectstepsNumber                      //11
                );

                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
                
                cmd.Connection = Connection;
                Connection.Open();
                Int64 result = (Int64)cmd.ExecuteScalar();
                return result;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static List<String> GetINVStepList(Int32 ProjectNumber, Int32 SubProjectNumber)
        {
            List<String> StepList = new List<string>();
            Int64 NumOfSteps = GetINVNumOfSteps(ProjectNumber, SubProjectNumber);
            for (int i = 1; i <= NumOfSteps; i++)
            {
                StepList.Add(GetINVStepName(ProjectNumber, SubProjectNumber, i));
            }
            return StepList;
        }

        public static string GetINVStepName(Int32 ProjectNumber, Int32 SubProjectNumber, Int64 N)
        // Stepname of step N in current project and subproject
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    beschrijving
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //JOIN
                //    subprojectsteps
                //ON
                //    subprojectsteps.subproject_id=subprojecten.id
                //WHERE 
                //    projects.number='P080591' 
                //AND
                //    subprojecten_subnumber.subnumber='3'
                //ORDER BY subprojectsteps.volgorde ASC
                //LIMIT [stepnumber],1

                String query = String.Format(
                    "SELECT " +
                    "{0}" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " JOIN " +
                    " {10} " +
                    " ON " +
                    "{10}.{5}={1}.id" +
                    " WHERE " +
                    "{2}.{6}='I{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'" +
                    " ORDER BY {10}.{11} ASC " +
                    " LIMIT {12}, 1 ",
                    FSubprojectstepsName,                       //0
                    TSubprojects,                               //1
                    TProjects,                                  //2
                    FSubProjectsProject_id,                     //3
                    TSubproject_SubprojectNumber,               //4
                    FSubproject_SubprojectnumberSubproject_id,  //5
                    FProjectsNumber,                            //6
                    ProjectNumber,                         //7
                    FSubproject_SubprojectnumberSubnumber,      //8
                    SubProjectNumber,                      //9
                    TSubprojectsteps,                           //10
                    FSubprojectstepsNumber,                     //11
                    N - 1                           //12
                );

                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
               
                cmd.Connection = Connection;
                Connection.Open();
                string result = (string)cmd.ExecuteScalar();
                result = result.Replace("\t", " - ").Replace("\r", " - ").Replace("\n", " - ");
                if (result == null)
                    return "n/a";
                else
                    return result;
            }
            catch (Exception e)
            {
                return "ERROR : " + e.Message;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }



        public static Int32 SubProjectMIDSTableID(Int32 ProjectNumber, Int32 SubProjectNumber)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    id
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //WHERE 
                //    projects.number='P080799' 
                //AND
                //    subprojecten_subnumber.subnumber='2'

                String query = String.Format(
                    "SELECT " +
                    "subprojecten.id" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " WHERE " +
                    "{2}.{6}='P{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'",
                    FSubProjectsName,
                    TSubprojects,
                    TProjects,
                    FSubProjectsProject_id,
                    TSubproject_SubprojectNumber,
                    FSubproject_SubprojectnumberSubproject_id,
                    FProjectsNumber,
                    ProjectNumber,
                    FSubproject_SubprojectnumberSubnumber,
                    SubProjectNumber
                );
                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();
                Int32 result = (Int32)cmd.ExecuteScalar();
                return result;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static Int32 SubINVProjectMIDSTableID(Int32 ProjectNumber, Int32 SubProjectNumber)
        {
            MySqlConnection Connection = null;
            try
            {
                // Query example
                //SELECT
                //    id
                //FROM 
                //    subprojecten
                //JOIN
                //    projects
                //ON
                //    projects.id=subprojecten.project_id
                //JOIN
                //    subprojecten_subnumber
                //ON
                //    subprojecten.id=subprojecten_subnumber.subproject_id
                //WHERE 
                //    projects.number='P080799' 
                //AND
                //    subprojecten_subnumber.subnumber='2'

                String query = String.Format(
                    "SELECT " +
                    "subprojecten.id" +
                    " FROM " +
                    "{1}" +
                    " JOIN " +
                    "{2}" +
                    " ON " +
                    "{2}.id={1}.{3}" +
                    " JOIN " +
                    "{4}" +
                    " ON " +
                    "{1}.id={4}.{5}" +
                    " WHERE " +
                    "{2}.{6}='I{7:000000}'" +
                    " AND " +
                    "{4}.{8}='{9}'",
                    FSubProjectsName,
                    TSubprojects,
                    TProjects,
                    FSubProjectsProject_id,
                    TSubproject_SubprojectNumber,
                    FSubproject_SubprojectnumberSubproject_id,
                    FProjectsNumber,
                    ProjectNumber,
                    FSubproject_SubprojectnumberSubnumber,
                    SubProjectNumber
                );
                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
                Console.WriteLine(query.ToString());
                cmd.Connection = Connection;
                Connection.Open();
                Int32 result = (Int32)cmd.ExecuteScalar();
                return result;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }
        }

        public static Color RowColor(Int32 ChamberID)
        {
            Color color = Color.White;

            MySqlConnection Connection = null;
            try
            {
                string query = String.Format("SELECT row_color FROM inventory WHERE nummer = {0}", ChamberID);
                Connection = GetConnection();
                MySqlCommand cmd = new MySqlCommand(query);
                cmd.Connection = Connection;
                Connection.Open();

                String sColor = String.Format(" {0}", (string)cmd.ExecuteScalar()).Trim().ToLower();

                switch (sColor)
                {
                    case "blue":
                        color = Color.FromArgb(191, 226, 248);
                        break;
                    case "cyan":
                        color = Color.FromArgb(196, 249, 235);
                        break;
                    case "grey":
                        color = Color.FromArgb(235, 243, 253);
                        break;
                    case "green":
                        color = Color.FromArgb(197, 249, 199);
                        break;
                    case "orange":
                        color = Color.FromArgb(249, 225, 196);
                        break;
                    case "pink":
                        color = Color.Pink;
                        break;
                    case "purple":
                        color = Color.FromArgb(208, 195, 249);
                        break;
                    case "yellow":
                        color = Color.FromArgb(249, 243, 195);
                        break;
                    default:
                        color = Color.White;
                        break;
                }
                if (color == null)
                    return Color.White;
                else
                    return color;
            }
            catch
            {
                return Color.White;
            }
            finally
            {
                if (Connection != null)
                    Connection.Close();
            }

        }


    // use the 2 functions below to find INVENTORY projects and chambers

        public static Project GetINVProject(int project, int subproject, int step)
        {
            Project project2 = new Project();
            project2.ProjectID = project;
            project2.SubProject = subproject;
            project2.Step = step;
            MySqlConnection mySqlConnection = null;
            try
            {
                //OUD: string cmdText = $"SELECT projects.id as pid, projects.name as pname, relations.id as rid, relations.name as rname FROM projects join relations on relations.id = customer_id WHERE number='P{project2.MIDSProject:000000}'";
                string cmdText = $"SELECT projects.id as pid, projects.name as pname,  relations.id as rid, relations.name as rname FROM projects join relations on relations.id = customer_id WHERE number='I{project2.ProjectID:000000}'";
                Console.WriteLine(cmdText);
                mySqlConnection = GetConnection();
                MySqlCommand mySqlCommand = new MySqlCommand(cmdText);
                mySqlCommand.Connection = mySqlConnection;
                mySqlConnection.Open();
                MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();

                if (mySqlDataReader.HasRows)
                {
                    while (mySqlDataReader.Read())
                    {
                        Console.WriteLine(mySqlDataReader["pname"].ToString());
                        Console.WriteLine(mySqlDataReader["rname"].ToString());

                        project2.ProjectDescription = mySqlDataReader["pname"].ToString().Replace(Environment.NewLine, " | ");
                        project2.Customer = mySqlDataReader["rname"].ToString().Replace(Environment.NewLine, " | ");
                        _DB_project_id = int.Parse(mySqlDataReader["pid"].ToString());
                        _DB_customer_id = int.Parse(mySqlDataReader["rid"].ToString());
                    }
                }
                else
                {
                    project2.ProjectDescription = "n/a";
                    project2.Customer = "n/a";
                }

                mySqlDataReader.Close();
            }
            catch (Exception ex)
            {
                project2.ProjectDescription = "Exception: " + ex.Message;
                project2.Customer = "Exception: " + ex.Message;
            }
            finally
            {
                mySqlConnection?.Close();
            }

            try
            {
                //OUD: string cmdText = "SELECT naam, subprojecten.id as id FROM subprojecten JOIN projects ON projects.id=subprojecten.project_id JOIN subprojecten_subnumber ON ";
                //cmdText += "subprojecten.id=subprojecten_subnumber.subproject_id WHERE projects.number=";
                //cmdText += $"'P{project2.MIDSProject:000000}' ";
                //cmdText = cmdText + "AND subprojecten_subnumber.subnumber=" + project2.MIDSSubProject;
                string cmdText = "SELECT naam, subprojecten.id as id FROM subprojecten JOIN projects ON projects.id=subprojecten.project_id JOIN subprojecten_subnumber ON ";
                cmdText += "subprojecten.id=subprojecten_subnumber.subproject_id WHERE projects.number=";
                cmdText += $"'I{project2.ProjectID:000000}' ";
                cmdText = cmdText + "AND subprojecten_subnumber.subnumber=" + project2.SubProject;
                mySqlConnection = GetConnection();
                MySqlCommand mySqlCommand = new MySqlCommand(cmdText);
                mySqlCommand.Connection = mySqlConnection;
                mySqlConnection.Open();
                MySqlDataReader mySqlDataReader2 = mySqlCommand.ExecuteReader();
                if (mySqlDataReader2.HasRows)
                {
                    while (mySqlDataReader2.Read())
                    {
                        project2.SubProjectDescription = mySqlDataReader2["naam"].ToString().Replace(Environment.NewLine, " | ");
                        _DB_subproject_id = int.Parse(mySqlDataReader2["id"].ToString());
                        Console.WriteLine(_DB_subproject_id);
                        Console.WriteLine(project2.Step);
                    }
                }
                else
                {
                    project2.SubProjectDescription = "n/a";
                }

                mySqlDataReader2.Close();
            }
            catch (Exception ex2)
            {
                project2.SubProjectDescription = "Exception : " + ex2.Message;
            }
            finally
            {
                mySqlConnection?.Close();
            }

            try
            {
                string cmdText = "SELECT id, beschrijving, s_in, s_out, s_fail, use_tested_fields FROM `subprojectsteps` WHERE subproject_id = " + _DB_subproject_id;
                cmdText = cmdText + " ORDER BY subprojectsteps.volgorde ASC LIMIT " + (project2.Step - 1) + ",1";
                mySqlConnection = GetConnection();
                MySqlCommand mySqlCommand = new MySqlCommand(cmdText);
                mySqlCommand.Connection = mySqlConnection;
                mySqlConnection.Open();
                MySqlDataReader mySqlDataReader3 = mySqlCommand.ExecuteReader();
                if (mySqlDataReader3.HasRows)
                {
                    while (mySqlDataReader3.Read())
                    {
                        _DB_step_id = int.Parse(mySqlDataReader3["id"].ToString());
                        Console.WriteLine(mySqlDataReader3["beschrijving"].ToString());
                        Console.WriteLine(_DB_step_id);

                        string text = mySqlDataReader3["beschrijving"].ToString().Replace(Environment.NewLine, " | ");
                        text = (project2.StepDescription = text.Replace(Environment.NewLine, " "));

                        project2.StepDescription = mySqlDataReader3["beschrijving"].ToString();

                        /*
                        if (int.Parse(mySqlDataReader3["use_tested_fields"].ToString()) > 0)
                        {
                            int num = int.Parse(mySqlDataReader3["s_in"].ToString());
                            int num2 = int.Parse(mySqlDataReader3["s_out"].ToString());
                            int num3 = int.Parse(mySqlDataReader3["s_fail"].ToString());
                            project2.UseTPF = true;
                            project2.TestPassFail = new int[3] { num, num2, num3 };
                        }
                        */
                    }
                }
                else
                {
                    project2.StepDescription = "n/a";
                }

                mySqlDataReader3.Close();
            }
            catch (Exception ex3)
            {
                project2.StepDescription = "Exception : " + ex3.Message;
            }
            finally
            {
                mySqlConnection?.Close();
            }

            return project2;
        }

        public static Chamber GetPlannedINVChamber(int project, int subproject, int step)
        {
            Chamber chamber = new Chamber();
            GetProject(project, subproject, step);
            MySqlConnection mySqlConnection = null;
            try
            {
                Console.WriteLine(_DB_step_id);
                string cmdText = "SELECT inventory.id as iid, nummer, beschrijving FROM inventory_step_planning JOIN inventory ON inventory.id = inventory_step_planning.inventory_id WHERE step_id = " + _DB_step_id;
                Console.WriteLine(cmdText);
                mySqlConnection = GetConnection();
                MySqlCommand mySqlCommand = new MySqlCommand(cmdText);
                mySqlCommand.Connection = mySqlConnection;
                mySqlConnection.Open();
                MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
                if (mySqlDataReader.HasRows)
                {
                    while (mySqlDataReader.Read())
                    {
                        Console.WriteLine(mySqlDataReader["iid"].ToString());
                        _DB_chamber_id = int.Parse(mySqlDataReader["iid"].ToString());
                        chamber.MIDS = int.Parse(mySqlDataReader["nummer"].ToString());
                        chamber.Description = mySqlDataReader["beschrijving"].ToString();
                        Console.WriteLine(chamber.MIDS.ToString());
                        Console.WriteLine(chamber.Description);
                    }
                }
                else
                {
                    chamber.MIDS = 0;
                    chamber.Description = "n/a";
                }

                mySqlDataReader.Close();
                return chamber;
            }
            catch (Exception ex)
            {
                chamber.MIDS = 0;
                chamber.Description = "Exception : " + ex.Message;
                return chamber;
            }
            finally
            {
                mySqlConnection?.Close();
            }
        }



    }
}
