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

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

        public override Section Find(int sectionId)
        {
            string query = "SELECT S.Id, S.Nazwa, T.Id, T.Symb, T.Symb2, T.max_rabat AS MaxDiscount, T.InvoiceProviderId FROM dbo.Grzbiety S INNER JOIN dbo.[Lista Tytułów] T ON S.TytulId=T.Id WHERE S.Id={0}";
            query = string.Format(query, sectionId);

            try
            {
                _connection.Open();
                _command = new SqlCommand(query, _connection);
                _reader = _command.ExecuteReader();
                if (_reader != null)
                {
                    if (_reader.Read())
                        return new Section(_reader.GetInt32(0),
                                           new Title(_reader.GetInt32(2), _reader.GetString(3), _reader.GetString(4), _reader.GetDouble(5), _reader.GetInt32(6)), 
                                           _reader.GetString(1));
                }
            }
            finally
            {
                CleanUp();
            }
            return null;

        }


        public List<Section> FindAllActiveByTitle(Title title)
        {
            string query = "SELECT Id, Nazwa, Active FROM Grzbiety WHERE tytulid={0} AND Active=1 ORDER BY Id";
            query = string.Format(query, title.Id);

            List<Section> sections = new List<Section>();

            try
            {
                _connection.Open();
                _command = new SqlCommand(query, _connection);
                _reader = _command.ExecuteReader();
                if (_reader != null)
                {
                    while (_reader.Read())
                    {
                        sections.Add(new Section(_reader.GetInt32(0), title, _reader.GetString(1)));
                    }
                }
            }
            finally
            {
                CleanUp();
            }
            return sections;
        }

        public List<Module> FindModulesBySection(Section section)
        {
            if (section == null)
                return new List<Module>();

            ModuleRepository moduleRepository = new ModuleRepository(_connectionString);
            return moduleRepository.FindAllActiveBySection(section);
        }
    }
}