using BoredCareers.Entities;
using MySql.Data.MySqlClient;
using System.Data;
using System.Data.Common;

namespace BoredCareers.Services.DatabaseService {
    public partial class DatabaseService {

        public async Task<Employee[]> GetEmployees( int CompanyID ) {
            List<Employee> employees = new List<Employee>();
            using( MySqlConnection connection = GetConnection() ) {
                connection.Open();
                string command = @"
                SELECT *
                FROM Employee
                WHERE ID = @ID;
                ";

                MySqlCommand cmd = new MySqlCommand(command, connection);
                cmd.Parameters.AddWithValue("@ID", CompanyID);
                
                using( DbDataReader reader = await cmd.ExecuteReaderAsync() ) {
                    while( await reader.ReadAsync() ) {
                        if( reader == null ) { break; }
                        int _id = reader.GetInt32("ID");
                        int _accountid = reader.GetInt32("AccountID");
                        int _companyid = reader.GetInt32("CompanyID");

                        employees.Add(new Employee() {
                            ID = _id,
                            AccountID = _accountid,
                            CompanyID = _companyid
                        });
                    }
                }
            }
            return employees.ToArray();
        }

        public async Task SetEmployee( Employee employee ) {
            using( MySqlConnection connection = GetConnection() ) {
                connection.Open();

                string command = @"
                INSERT INTO Employee
                (ID,AccountID,CompanyID)
                VALUES
                (@ID,@AccountID,@CompanyID);
                ON DUPLICATE KEY UPDATE
                AccountID = @AccountID,
                CompanyID = @CompanyID;
                ";

                MySqlCommand cmd = new MySqlCommand( command , connection);
                cmd.Parameters.AddWithValue("@ID", employee.ID);
                cmd.Parameters.AddWithValue("@AccountID", employee.AccountID);
                cmd.Parameters.AddWithValue("@CompanyID", employee.CompanyID);

                await cmd.ExecuteNonQueryAsync();
            }
        }

        public async Task DeleteEmployee( int EmployeeID ) {
            using( MySqlConnection connection = GetConnection() ) {
                MySqlCommand cmd;
                connection.Open();

                string command = @"
                DELETE FROM Employee WHERE ID = @ID;
                ";
                cmd = new MySqlCommand( command, connection );
                cmd.Parameters.AddWithValue("@ID", EmployeeID);

                await cmd.ExecuteNonQueryAsync();
            }
        }

    }
}
