using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace RadScheduler
{
    public class ConferenceRepository
    {
        private string _jsonPresentationsFileName = "presentations.json";
        private string _jsonResourceFileName = @"StarterData\resources.json";

        private ObservableCollection<Presentation> _presentations;
        private ObservableCollection<Room> _rooms;

        public ObservableCollection<Room> Rooms
        {
            get
            {
                return this._rooms;
            }
            set
            {
                this._rooms = value;
            }
        }

        public ObservableCollection<Presentation> Presentations
        {
            get
            {
                return this._presentations;
            }
            set
            {
                this._presentations = value;
            }
        }

        public ConferenceRepository()
        {
            if (File.Exists(_jsonPresentationsFileName))
            {
                Presentations = JsonConvert.DeserializeObject<ObservableCollection<Presentation>>(File.ReadAllText(_jsonPresentationsFileName));
            }
            else
            {
                Presentations = new ObservableCollection<Presentation>();
            }

            if (File.Exists(_jsonResourceFileName))
            {
                Rooms = JsonConvert.DeserializeObject<ObservableCollection<Room>>(File.ReadAllText(_jsonResourceFileName));
            }
            else
            {
                Rooms = new ObservableCollection<Room>();
            }
        }

        public void PersistRepository()
        {
            using (StreamWriter sw = new StreamWriter(_jsonPresentationsFileName, false))
            {
                //save the presentations
                string presentationJson = JsonConvert.SerializeObject(Presentations, Formatting.Indented);
                sw.Write(presentationJson);
                sw.Close();
            }
        }
    }
}
