﻿using DynamicsCRMWebResourceManager.Storage;
using DynamicsCRMWebResourceManager.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using DynamicsCRMWebResourceManager.Controllers;

namespace DynamicsCRMWebResourceManager.Storage
{
    public class Repository
    {
        private static string dataFilePath = "data.xml";

        private DataContractSerializer xmlSerializer;

        private List<ConnectionConfiguration> configs;

        public Repository()
        {
            xmlSerializer = new DataContractSerializer(typeof(List<ConnectionConfiguration>));
            configs = GetData();
        }

        private void SaveData()
        {
            Controller.WriteToOutput("Saving to 'data.xml' file started.");
            try
            {                              
                using (FileStream fileStream = File.Open(dataFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    xmlSerializer.WriteObject(fileStream, configs);                    
                }
                Controller.WriteToOutput("Saving to 'data.xml' file finished.");
            }
            catch (Exception ex)
            {
                Controller.WriteToOutput(String.Format("Error occured during saving to 'data.xml' file. Additional information: {0}", ex.Message));
                Controller.WriteToOutput("Saving to 'data.xml' file failed.");
            }
        }

        private List<ConnectionConfiguration> GetData()
        {
            Controller.WriteToOutput("Loading configs from 'data.xml' file started.");
            List<ConnectionConfiguration> data = null;
            if (File.Exists(dataFilePath))
            {
                try
                {
                    using (FileStream fileStream = File.Open(dataFilePath, FileMode.Open, FileAccess.Read))
                    {
                        data = xmlSerializer.ReadObject(fileStream) as List<ConnectionConfiguration>;
                    }
                    Controller.WriteToOutput("Loading configs from 'data.xml' file finished.");
                }
                catch (Exception ex)
                {
                    Controller.WriteToOutput(String.Format("Error during loading data from 'data.xml'. It is possible that the file is corrupted. If so, removal of data.xml will help but you will be forced to link web resources over again. Additional information: {0}", ex.Message));
                }                
            }    
            if (data == null)
            {
                data = new List<ConnectionConfiguration>();
                Controller.WriteToOutput("No configs loaded.");
            }
            return data;   
        }

        public ConnectionConfiguration GetConfig(string filePath)
        {
            if (filePath == null)
            {
                return null;
            }
            foreach (ConnectionConfiguration cc in configs)
            {
                if (cc.SolutionPath == filePath)
                {
                    return cc;
                }
            }
            ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration()
            {
                SolutionPath = filePath
            };
            configs.Add(connectionConfiguration);
            return connectionConfiguration;
        }

        public void Update()
        {
            this.SaveData();
        }
    }
}
