using ActionGame.GameArtifacts.Models.Game;
using Newtonsoft.Json;
using System;
using System.IO;
using System.IO.IsolatedStorage;


namespace ActionGame.GameArtifacts.Operators
{
    public class GameStateSaver
    {
        private GameState gameState;

        public GameStateSaver(GameState gameState)
        {
            this.gameState = gameState;
        }


        public Boolean Save()
        {
            IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isolatedFileStream = null;
            String filename = "actiongame.sav";

            try
            {
                isolatedFileStream = savegameStorage.OpenFile(filename, System.IO.FileMode.Create);
            }
            catch (IsolatedStorageException)
            {
                return false;
            }

            if(isolatedFileStream != null)
            {
                StreamWriter writer = new StreamWriter(isolatedFileStream);

                SaveContainer container = new SaveContainer()
                {
                    CharacterStats = gameState.Player.CharacterStats,
                    WorldPosition = gameState.Player.WorldPosition,
                    VariableState = gameState.VariableState,
                    Inventory = new SaveInventoryContainer(gameState.Player.Inventory)
                };

                String json = JsonConvert.SerializeObject(container);

                writer.Write(json);

                writer.Close();
                isolatedFileStream.Close();
            }

            return true;
        }

    }
}
