using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Core.Db;
using Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Services
{
    public class BaseService<T> : IBaseService<T>
    where T:BaseEntity
    {
        public readonly PanakDbContext _db;

        public BaseService(IServiceProvider serviceProvider)
        {
            _db = serviceProvider.GetService<PanakDbContext>();
        }

        public virtual void Add(T entity)
        {
            _db.Add(entity);
            _db.SaveChanges();

        }

        public virtual void Update(T entity)
        {
            entity.ModifyDate=DateTime.Now;
            _db.SaveChanges();
        }

        public virtual void Delete(Guid id)
        {
            DeleteWithoutSave(id);
            _db.SaveChanges();

        }
        public virtual void DeleteWithoutSave(Guid id)
        {
            var item = GetById(id);
            _db.Remove(item);

        }
        public virtual void SaveChanges()
        {
            _db.SaveChanges();
        }

        public virtual IQueryable<T> GetQueryable()
        {
            return _db.Set<T>().AsQueryable();
        }

        public virtual IQueryable<T> GetWithPaging(int page = 1, int pageSize = 100)
        {
            return GetQueryable().Skip(Math.Max(0, (page - 1) * pageSize)).Take(pageSize);
        }

        public virtual T GetById(Guid id)
        {
            return _db.Set<T>().FirstOrDefault(x=>x.Id==id);
        }

        public virtual void AddOrUpdate(T entity)
        {
            if(entity.Id!=Guid.Empty)
                Update(entity);
            else
                Add(entity);
        }

        public virtual bool CanBeDeleted(Guid id)
        {
            return true;
        }
    }
}
