using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
using System.Web;

namespace iBemsDataService.Util
{
    public class QueryManager<TModel> where TModel : class, new()
    {
        DbContext DbContext { get; set; }
        public QueryManager( DbContext dbContext )
        {
            this.DbContext = dbContext;
        }

        public bool Delete<TDbSet>( TDbSet dbSet , TModel model , bool isAttach = true )
            where TDbSet : DbSet<TModel>
        {
            try
            {
                if (isAttach) dbSet.Attach( model );
                dbSet.Remove( model );
            }
            catch( DbUpdateException )
            {
                throw;
            }
            return true;
        }

        public bool Delete<TDbSet>( TDbSet dbSet , IQueryable queryToDelete )
            where TDbSet : DbSet<TModel>
        {
            try
            {
                foreach( TModel deleteItem in queryToDelete )
                {
                    dbSet.Remove( deleteItem );
                }
            }
            catch( DbUpdateException )
            {
                throw;
            }
            return true;
        }

        public bool DeleteAndInsert<TDbSet , TList>( TDbSet dbSet , TList list , IQueryable queryToDelete )
            where TDbSet : DbSet<TModel>
            where TList : IList
        {
            try
            {
                foreach( TModel deleteItem in queryToDelete )
                {
                    dbSet.Remove( deleteItem );
                }

                //Type itemType = list.GetType().GetGenericTypeDefinition();
                PropertyInfo[] listItemProperties = null;
                var modelType = typeof( TModel );
                
                foreach( var item in list )
                {
                    if (item == null)
                        break;
                    var model = new TModel();
                    if ( listItemProperties == null )
                    {
                        listItemProperties = item.GetType().GetProperties();
                    }
                    foreach( var p in listItemProperties )
                    {
                        modelType.GetProperty( p.Name ).SetValue( model , p.GetValue( item ) );
                    }
                    dbSet.Add( model );
                }
                this.DbContext.SaveChanges();
            }
            catch( DbUpdateException )
            {
                //if( FmsWorkOrderToToFacilityExists( FmsWorkOrderToToFacility.SiteId ) )
                //{
                //    return Conflict();
                //}
                //else
                {
                    throw;
                }
                //                return false;
            }
            return true;
        }
    }
}