using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using UnivateProperties_API.Context;
using UnivateProperties_API.Model.Region;

namespace UnivateProperties_API.Repository.Region
{
    public class CityRepository : ICityRepository
    {
        private readonly DataContext dBContext;

        public CityRepository(DataContext _dBContext)
        {
            dBContext = _dBContext;
        }

        public List<City> Get(Func<City, bool> where)
        {
            return dBContext.Cities.Where(where).ToList();
        }        

        public List<City> GetAll()
        {
            return dBContext.Cities.ToList();
        }

        public List<City> GetBy(string province)
        {
            var provObj = dBContext.Provinces.Where(p => p.Description == province).First();
            if (provObj != null)
                return dBContext.Cities.Where(c => c.ProvinceId == provObj.Id).OrderBy(c => c.Description).ToList();
            else
                return null;
        }

        public City GetDetailed(Func<City, bool> first)
        {
            throw new NotImplementedException();
        }

        public List<City> GetDetailedAll()
        {
            throw new NotImplementedException();
        }

        public void Insert(City item)
        {
            dBContext.Cities.Add(item);
            Save();
        }

        public void Insert(IEnumerable<City> items)
        {
            foreach (var item in items)
            {
                dBContext.Cities.Add(item);
                Save();
            }
        }

        public void Remove(City item)
        {
            dBContext.Cities.Remove(item);
            Save();
        }

        public void Remove(IEnumerable<City> items)
        {
            foreach (var item in items)
            {
                dBContext.Cities.Remove(item);
            }
            Save();
        }

        public void RemoveAtId(int item)
        {
            var city = Get(x => x.Id == item).FirstOrDefault();
            if (city != null)
            {
                dBContext.Cities.Remove(city);
                Save();
            }
        }

        public void Save()
        {
            dBContext.SaveChanges();
        }

        public void Update(City item)
        {
            dBContext.Entry(item).State = EntityState.Modified;
            Save();
        }
    }
}