using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnivateProperties_API.Containers.Property;
using UnivateProperties_API.Context;
using UnivateProperties_API.Model.Properties;

namespace UnivateProperties_API.Repository.Properties
{
    public class PropertyImageRepository : IPropertyImageRepository
    {
        private readonly DataContext dBContext;

        public PropertyImageRepository(DataContext _dBContext)
        {
            dBContext = _dBContext;
        }
        public List<PropertyImage> Get(Func<PropertyImage, bool> where)
        {
            var images = dBContext.PropertyImages.Where(where).OrderByDescending(i => i.IsDefault).ThenBy(i => i.Id).ToList();

            var url = dBContext.Location.FirstOrDefault()?.SiteURL;

            foreach (PropertyImage img in images)
            {
                if (!img.Image.StartsWith("data:image"))
                {
                    if (!string.IsNullOrEmpty(url))
                        img.Image = ImageFormatter.ImageToURL(img.Image, url);
                    else
                        img.Image = ImageFormatter.ImageToBase64(img.Image);
                }
            }

            return images;
        }

        public List<PropertyImage> GetAll()
        {
            return dBContext.PropertyImages.ToList();
        }

        public PropertyImage GetDetailed(Func<PropertyImage, bool> first)
        {
            return dBContext.PropertyImages.FirstOrDefault(first);
        }

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

        public List<string> GetImages(int PropertyId)
        {
            var images = (from p in dBContext.PropertyImages
                          where p.PropertyId == PropertyId
                          orderby p.IsDefault descending
                          select p.Image).ToList();            

            List<string> formated = new List<string>();

            var url = dBContext.Location.FirstOrDefault()?.SiteURL;

            foreach (string img in images)
            {
                if (!img.StartsWith("data:image"))
                {
                    if (!string.IsNullOrEmpty(url))
                        formated.Add(ImageFormatter.ImageToURL(img, url));
                    else
                        formated.Add(ImageFormatter.ImageToBase64(img));
                }
                else
                    formated.Add(img);
            }

            return formated;
        }

        public void Insert(PropertyImage item)
        {
            dBContext.PropertyImages.Add(item);
            Save();
        }

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

        public void Remove(PropertyImage item)
        {
            dBContext.PropertyImages.Remove(item);
            Save();
        }

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

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

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

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

        public int NewId()
        {
            // Not sure if properties need it
            return 0;
        }

        public void Update(NewPropertyImages propertyImages)
        {
            if (propertyImages.Images != null)
            {                
                bool saveFiles = false;
                var loc = dBContext.Location.FirstOrDefault()?.PropertyImageLocation;
                if (!string.IsNullOrEmpty(loc))
                {
                    saveFiles = true;
                    if (loc.EndsWith("\\"))
                    {
                        loc = loc.Substring(0, loc.Length - 1);
                    }
                    loc += string.Format("\\{0}", propertyImages.PropertyId);
                    if (!Directory.Exists(loc))
                    {
                        Directory.CreateDirectory(loc);
                    }
                }

                var lastID = dBContext.PropertyImages.Max(i => i.Id) + 1;

                foreach (var image in propertyImages.Images)
                {                   
                    var newImage = new PropertyImage
                    {                        
                        PropertyId = propertyImages.PropertyId
                    };
                    if (saveFiles)
                    {
                        string path = ImageFormatter.Base64ToImage(image.Image, loc, lastID.ToString());
                        newImage.Image = path;
                        lastID++;
                    }
                    else
                    {
                        newImage.Image = image.Image;
                    }
                    dBContext.PropertyImages.Add(newImage);
                }

                Save();
            }
        }

        public void UpdateToPhysical()
        {            
            bool saveFiles = false;
            var loc = dBContext.Location.FirstOrDefault()?.PropertyImageLocation;
            if (!string.IsNullOrEmpty(loc))
            {
                saveFiles = true;
                if (loc.EndsWith("\\"))
                {
                    loc = loc.Substring(0, loc.Length - 1);
                }
            }

            if (saveFiles)
            {
                var images = dBContext.PropertyImages.ToList();
                foreach (var image in images)
                {
                    string filePath = string.Format("{0}\\{1}", loc, image.PropertyId );
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    string path = ImageFormatter.Base64ToImage(image.Image, filePath, image.Id.ToString());
                    image.Image = path;
                }

                Save();
            }
        }
    }
}