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

namespace Baza_Reklam.Classes.Repositories
{
    public class UserAgencyRepository
    {
        public static 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>();

            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader reader = null;
            try
            {
                conn = new SqlConnection(ConnString.getConnString().Value);
                conn.Open();
                cmd = new SqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@userId", userId);
                reader = cmd.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
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (cmd != null) cmd.Dispose();
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }

            }
            return userAgencies;
        }
    }
}