﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using System.Data;
using Dapper;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace DataAccess.AutoMerge
{
    public class Select : Base.ISelect
    {
        private readonly Database database;

		public Select(Database database)
        {
			this.database = database;
        }

        public List<Entities.AutoMerge> Execute(out int total, int pageSize = -1, int pageNumber = -1)
        {
            List<Entities.AutoMerge> merges = new List<Entities.AutoMerge>();

            StringBuilder query = new StringBuilder();

            if(pageSize == -1 || pageNumber == -1)
            {
                query.AppendLine("SELECT * FROM [dbo].[AutoMerge]");
            }
            else
            {
                query.AppendLine("SELECT * FROM [dbo].[AutoMerge] ORDER BY [Id] OFFSET (@pageSize * (@pageNumber - 1)) ROWS FETCH NEXT @pageSize ROWS ONLY");
            }

            query.AppendLine("SELECT COUNT([Id]) FROM [dbo].[AutoMerge]");

			using (IDbConnection connection = database.CreateConnection())
			{
                using (var multi = connection.QueryMultiple(query.ToString(), new { pageNumber, pageSize }))
                {
                    merges = multi.Read<Entities.AutoMerge>().ToList();
                    total = multi.Read<int>().First();
                }
			}

            return merges;
        }

        public Entities.AutoMerge Execute(int id)
        {
			using (IDbConnection connection = database.CreateConnection())
			{
				return connection.Query<Entities.AutoMerge>("SELECT * FROM [dbo].[AutoMerge] WHERE [Id] = @id", new { id }).FirstOrDefault();
			}
        }
    }
}
