using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace LocalFolderSample.DataModel
{
    public class FileRepository : IDataRepository
    {
        StorageFolder folder = ApplicationData.Current.RoamingFolder;
        string fileName = "customers.json";
        ObservableCollection<Customer> customers;

        public FileRepository()
        {
            Initialize();
        }

        private void Initialize()
        {
        }

        public async Task<ObservableCollection<Customer>> Load()
        {
            var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

            string fileContents = string.Empty;
            if (file != null)
            {
                fileContents = await FileIO.ReadTextAsync(file);
            }

            IList<Customer> customersFromJSON =
                JsonConvert.DeserializeObject<List<Customer>>(fileContents)
                    ?? new List<Customer>();

            customers = new ObservableCollection<Customer>(customersFromJSON);

            return customers;
        }

        public Task Add(Customer customer)
        {
            customers.Add(customer);
            return WriteToFile();
        }

        public Task Remove(Customer customer)
        {
            customers.Remove(customer);
            return WriteToFile();
        }

        public Task Update(Customer customer)
        {
            var oldCustomer = customers.FirstOrDefault(c => c.Id == customer.Id);
            if (oldCustomer == null)
            {
                throw new System.ArgumentException("Customer not found.");
            }
            customers.Remove(oldCustomer);
            customers.Add(customer);
            return WriteToFile();
        }

        private async Task<StorageFile> OpenFileAsync()
        {
            return await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);
        }

        private Task WriteToFile()
        {
            return Task.Run(async () => 
            {
                string JSON = JsonConvert.SerializeObject(customers);
                var file = await OpenFileAsync();
                await FileIO.WriteTextAsync(file, JSON);
            });
        }
    }
}