using System;
using System.Collections.Generic;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace it_projekt
{
    class Database
    {
        private static Database _database;
        public List<Person> Persons { get; set; }
        private Database(string username, string password)
        {
            string connectionString = "server=localhost;port=3306;database=stammdaten;User Id=" + username + ";Password=" + password + ";";
            MySqlConnection connection = new MySqlConnection(connectionString);
            try
            {
                connection.Open();

                string sql = 
                    "SELECT stammdaten.id,stammdaten.firstname, stammdaten.lastname, stammdaten.creationdate, abteilung.kuerzel, abteilung.name " +
                    "FROM `stammdaten` JOIN abteilung " +
                    "WHERE abteilungs_id = abteilung.id;";
                MySqlCommand cmd = new MySqlCommand(sql, connection);
                MySqlDataReader rdr = cmd.ExecuteReader();
                Persons = new List<Person>();
                while (rdr.Read())
                {
                    Person p = new Person(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString(), DateTime.Parse(rdr[3].ToString()), rdr[4].ToString(), rdr[5].ToString());
                    Persons.Add(p);

                }
                rdr.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            connection.Close();
        }

        public static Database getDatabase(string username, string password)
        {
            if (_database == null)
            {
                _database = new Database(username, password);
            }
            return _database;
        }

        public static void resetDatabase()
        {
            _database = null;
        }
    }
}
