using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace ReadingAndWritingDemo.DataModel
{
    public class ViewModelBackup : INotifyPropertyChanged
    {
        public ViewModelBackup()
        {
            Customers = new List<Customer>();
        }
        private StorageFolder _currentFolder;
        public StorageFolder CurrentFolder
        {
            get { return _currentFolder; }
            set
            {
                _currentFolder = value;
                NotifyPropertyChanged("CurrentFolder");
            }
        }
        private IList<Customer> customers;
        public IList<Customer> Customers
        {
            get { return customers; }
            set
            {
                customers = value;
                NotifyPropertyChanged("Customers");
            }
        }
        public void LoadDocumentsLibrary()
        {
            CurrentFolder = KnownFolders.DocumentsLibrary;
        }
        public async Task<StorageFile> CreateFile(
            string subFolderName, string fileName)
        {
            if (CurrentFolder != null)
            {
                var folder = await CurrentFolder.CreateFolderAsync(
                    subFolderName, CreationCollisionOption.OpenIfExists);

                return await folder.CreateFileAsync(
                    fileName, CreationCollisionOption.ReplaceExisting).AsTask();
            }
            else
                return null;
        }

        public async Task<StorageFile> OpenFile(
            string subFolderName, string fileName)
        {
            if (CurrentFolder != null)
            {
                try
                {
                    var folder = await CurrentFolder.CreateFolderAsync(
                        subFolderName, CreationCollisionOption.OpenIfExists);

                    return await folder.GetFileAsync(fileName);
                }
                catch
                {
                    // Unfortunately necessary because GetFileAsync returns an exception
                    return null;
                }
            }
            else
                return null;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string p)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(p));
        }

    }
}
