using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Baza_Reklam.Classes.Model;

namespace Baza_Reklam.Classes.Repositories
{
    public class BargainRepository : Repository<Bargain>
    {
        private readonly string _connectionString;

        public BargainRepository(string connectionString)
        {
            _connectionString = connectionString;
        }

        public List<Bargain> FindAllActive()
        {
            const string query = "sp_GetAktywnePromocje";

            List<Bargain> bargains = new List<Bargain>();

            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader reader = null;
            try
            {
                conn = new SqlConnection(_connectionString);
                conn.Open();
                cmd = new SqlCommand(query, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        Bargain bargain = new Bargain();
                        bargain.Id = reader.GetInt32(0);
                        bargain.Name = reader.GetString(1);
                        bargain.IsActive = true;
                        bargains.Add(bargain);
                    }
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (cmd != null) cmd.Dispose();
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
            return bargains;
        }
    }
}
