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

namespace Baza_Reklam.Classes.Repositories
{
    public class UserAgencyRepository : Repository<UserAgency>
    {
        public UserAgencyRepository(string connectionString)
            : base(connectionString)
        {
        }

        public List<UserAgency> FindByUserId(int userId)
        {
            const string query = "SELECT UA.UserId, UA.AgencyId, UA.Name, A.Symbol AS AgencyName, UA.[Order] FROM dbo.UserAgency UA "
                                 + "INNER JOIN Agencje A ON A.Id_Agencji=UA.AgencyId "
                                 + "WHERE UA.UserId=@userId ORDER BY [Order]";

            
            List<UserAgency> userAgencies = new List<UserAgency>();

            try
            {
                _connection.Open();
                _command = new SqlCommand(query, _connection);
                _command.Parameters.AddWithValue("@userId", userId);
                _reader = _command.ExecuteReader();
                if (_reader != null)
                {
                    while (_reader.Read())
                    {
                        UserAgency userAgency = new UserAgency();
                        userAgency.UserId = userId;
                        userAgency.AgencyId = _reader.GetInt32(1);
                        userAgency.Name = _reader.GetString(2);
                        userAgency.AgencyName = _reader.GetString(3);
                        userAgency.Order = _reader.GetInt32(4);
                        userAgencies.Add(userAgency);
                    }
                }
            }
            finally
            {
                CleanUp();
            }
            return userAgencies;
        }
    }
}