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<JobListingSkill[]> GetJobListingSkills(int JobListingID) {
            List<JobListingSkill> joblistingskills = new List<JobListingSkill>();
            using (MySqlConnection connection = GetConnection()) {
                await connection.OpenAsync();
                string command = @"
                SELECT *
                FROM JobListingSkill
                WHERE JobListingID = @JobListingID;
                ";

                MySqlCommand cmd = new MySqlCommand(command, connection);
                cmd.Parameters.AddWithValue("@JobListingID", JobListingID);

                using (DbDataReader reader = await cmd.ExecuteReaderAsync()) {
                    while (await reader.ReadAsync()) {
                        if (reader == null) { break; }
                        int _id = reader.GetInt32("ID");
                        int _joblistingid = reader.GetInt32("JobListingID");
                        string _name = reader.GetString("Name");
                        string _description = reader.GetString("Description");

                        joblistingskills.Add(new JobListingSkill() {
                            ID = _id,
                            JobListingID = _joblistingid,
                            Name = _name,
                            Description = _description
                        });
                    }
                }
            }
            return joblistingskills.ToArray();
        }

        public async Task SetJobListingSkills( JobListingSkill jobListingSkill ) {
            using( MySqlConnection connection = GetConnection() ) {
                await connection.OpenAsync();
                string command = @"
                INSERT INTO JobListingSkill
                (ID,JobListingID,Name,Description)
                VALUES
                (@ID,@JobListingID,@Name,@Description)
                ON DUPLICATE KEY UPDATE
                JobListingID = @JobListingID,
                Name = @Name,
                Description = @Description;
                ";

                MySqlCommand cmd = new MySqlCommand( command , connection);
                cmd.Parameters.AddWithValue("@ID", jobListingSkill.ID);
                cmd.Parameters.AddWithValue("@JobListingID", jobListingSkill.JobListingID);
                cmd.Parameters.AddWithValue("@Name", jobListingSkill.Name);
                cmd.Parameters.AddWithValue("@Description", jobListingSkill.Description);

                await cmd.ExecuteNonQueryAsync();
            }
        }

    }
}
