using ActionGame.RawResources.Models;
using Microsoft.Xna.Framework.Content;
using System;
using System.Collections.Generic;
using System.IO;


namespace ActionGame.RawResources.Repository
{
    public class FileRawContentRepository<T> : IRawContentRepository<T>
    {
        private Dictionary<Int32, T> contentByKey;
        private Dictionary<String, T> contentByName;
        private ContentManager contentManager;


        public FileRawContentRepository(ContentManager contentManager, String filename)
        {
            this.contentManager = contentManager;

            this.contentByKey = new Dictionary<Int32, T>();
            this.contentByName = new Dictionary<String, T>();

            Load(filename);
        }


        public T GetContent(Int32 key)
        {
            T content = default(T);

            if (this.contentByKey.ContainsKey(key))
            {
                content = this.contentByKey[key];
            }

            return content;
        }


        public T GetContent(String name)
        {
            T content = default(T);

            if (this.contentByName.ContainsKey(name))
            {
                content = this.contentByName[name];
            }

            return content;
        }


        private void Load(String filename)
        {
            Stream stream = null;
            StreamReader reader = null;
            String line = null;
            String[] lineContents = null;
            RawResource item = null;

            stream = File.OpenRead(filename);
            reader = new StreamReader(stream);

            //skip first line
            reader.ReadLine();

            while ((line = reader.ReadLine()) != null)
            {
                lineContents = line.Split(',');

                if (lineContents[0].Equals("") == false)
                {
                    item = new RawResource()
                    {
                        Key = Int32.Parse(lineContents[0]),
                        FilePath = lineContents[1]
                    };

                    LoadContent(item);
                }
            }

            reader.Close();
        }


        private void LoadContent(RawResource item)
        {
            T c = default(T);

            c = this.contentManager.Load<T>(item.FilePath);

            this.contentByKey.Add(item.Key, c);
            this.contentByName.Add(item.FilePath, c);
        }

    }
}
