using ActionGame.GameResources.Models;
using System;
using System.Collections.Generic;
using System.IO;


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


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

            Load(filename);
        }


        public PlayerDefinition GetContent(Int32 key)
        {
            PlayerDefinition 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;

            PlayerDefinition playerDefinition = new PlayerDefinition();
            playerDefinition.StartPosition = new WorldPosition();

            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("CharacterSetKey")) playerDefinition.CharacterSetKey = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("StartMap")) playerDefinition.StartPosition.WorldMapKey = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("StartCellX")) playerDefinition.StartPosition.WorldCellX = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("StartCellY")) playerDefinition.StartPosition.WorldCellY = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("StartTileX")) playerDefinition.StartPosition.PositionX = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("StartTileY")) playerDefinition.StartPosition.PositionY = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("Health")) playerDefinition.Health = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("Attack")) playerDefinition.Attack = Int32.Parse(lineContents[1]);
                else if (lineContents[0].Equals("Defence")) playerDefinition.Defence = Int32.Parse(lineContents[1]);
            }

            reader.Close();

            this.ContentByKey.Add(0, playerDefinition);
            this.Keys.Add(0);
        }


    }
}
