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

namespace Baza_Reklam.Classes.Repositories
{
    public class AgentRepository : Repository<Agent>
    {
        public List<Agent> FindAllActive()
        {
            const string query = "SELECT Symbol FROM dbo.Agenci WHERE aktywny=1 ORDER BY Symbol";

            List<Agent> agents = new List<Agent>();

            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader reader = null;
            try
            {
                conn = new SqlConnection(ConnString.getConnString().Value);
                conn.Open();
                cmd = new SqlCommand(query, conn);
                reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        agents.Add(new Agent(reader.GetString(0).Trim().ToLower()));
                    }
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (cmd != null) cmd.Dispose();
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }

            }
            return agents;
        }

        public Agent FindByShortName(string shortName)
        {
            const string query = "SELECT Symbol, F_ROZ, InvoiceProviderId FROM dbo.Agenci WHERE F_ROZ=@shortName";
            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataReader reader = null;

            try
            {
                conn = new SqlConnection(ConnString.getConnString().Value);
                conn.Open();
                cmd = new SqlCommand(query, conn);
                reader = cmd.ExecuteReader();
                if (reader != null && reader.Read())
                    return new Agent(reader.GetString(0).Trim().ToLower(),
                                     reader.GetString(1).Trim().ToUpper(),
                                     reader.GetInt32(2));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (cmd != null) cmd.Dispose();
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }

            }
            return null;
        }
    }
}