using ActionGame.GameResources.Models;
using ActionGame.RawResources.Manager;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ActionGame.GameResources.Repository
{
    public class FileItemDefinitionRepository : IGameContentRepository<ItemDefinition>
    {
        private IDictionary<Int32, ItemDefinition> ContentByKey { get; set; }
        private IList<Int32> Keys { get; set; }


        public FileItemDefinitionRepository(String filename)
        {
            this.ContentByKey = new Dictionary<Int32, ItemDefinition>();
            this.Keys = new List<Int32>();

            Load(filename);
        }


        public ItemDefinition GetContent(Int32 key)
        {
            ItemDefinition content = null;

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

            return content;
        }


        public IList<Int32> GetKeys()
        {
            return this.Keys;
        }


        private void Load(String filename)
        {
            Stream stream = null;
            StreamReader reader = null;
            String line = null;
            String[] lineContents = 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)
                {
                    LoadContent(lineContents);
                }
            }

            reader.Close();
        }


        private void LoadContent(String[] lineContents)
        {
            ItemDefinition itemDefinition = null;

            itemDefinition = new ItemDefinition()
            {
                Key = Int32.Parse(lineContents[0]),
                Name = lineContents[1],
                ItemTypeKey = Int32.Parse(lineContents[2]),
                TextureKey = Int32.Parse(lineContents[3]),
                IsFixedPower = Boolean.Parse(lineContents[4]),
                Power = Int32.Parse(lineContents[5]),
                Description = lineContents[6],
                MaxCapacity = Int32.Parse(lineContents[7])
            };

            this.ContentByKey.Add(itemDefinition.Key, itemDefinition);
            this.Keys.Add(itemDefinition.Key);
        }


    }
}
