view api/Factories/Xml/WarFoundryXmlSaver.cs @ 95:6c6cfe5594fc

Re #118: Allow equipment amounts of "ratio" equipment to be define as absolute or ratio amounts * Create new "equipment selection" objects to track equipment selection amounts and cost * Create ratio version * Creat absolute amount version
author IBBoard <dev@ibboard.co.uk>
date Sun, 09 Aug 2009 10:34:09 +0000
parents 3ea0ab04352b
children 2f3cafb69799
line wrap: on
line source

// This file (WarFoundryXmlSaver.cs) is a part of the IBBoard.WarFoundry.API project and is copyright 2009 IBBoard.
//
// The file and the library/program it is in are licensed under the GNU LGPL license, either version 3 of the License or (at your option) any later version. Please see COPYING.LGPL for more information and the full license.

using System;
using System.Collections.Generic;
using System.IO;
using IBBoard.Lang;
using IBBoard.WarFoundry.API.Objects;

namespace IBBoard.WarFoundry.API.Factories.Xml
{
	public class WarFoundryXmlSaver
	{
		//FIXME: Rework to saving files in Zips
		private static WarFoundryXmlSaver saver;
		private static List<Type> saveAsTypes;
		private Dictionary<WarFoundryObject, string> savePaths = new Dictionary<WarFoundryObject,string>();
		
		public static WarFoundryXmlSaver GetSaver()
		{
			if (saver == null)
			{
				saveAsTypes = new List<Type>();
				saveAsTypes.Add(typeof(Army));
				saver = new WarFoundryXmlSaver();
			}
			
			return saver;
		}
		
		public bool SaveAs(WarFoundryObject toSave, string saveAsPath)
		{
			if (CanSaveType(toSave))
			{
				FileStream fs = null;
				bool success = false;
				
				try
				{
					fs = new FileStream(saveAsPath, FileMode.Create, FileAccess.Write);
					byte[] bytes = StringManipulation.StringToBytes(CreateXmlString(toSave));
					fs.Write(bytes, 0, bytes.Length);
					fs.Flush();
					savePaths.Add(toSave, saveAsPath);
					success = true;
				}
				finally
				{
					if (fs!=null && fs.CanWrite)
					{
						fs.Close();
					}
				}

				return success;
			}
			else
			{
				throw new ArgumentException("Cannot directly save objects of type "+toSave.GetType());
			}
		}
		
		public bool Save(WarFoundryObject toSave)
		{
			if (CanSave(toSave))
			{
				return SaveAs(toSave, savePaths[toSave]);
			}
			else
			{
				throw new InvalidOperationException("Cannot save an object that has not previously been saved using SaveAs");
			}
		}
		
		private string CreateXmlString(WarFoundryObject toSave)
		{
			return ""; //TODO: Create XML string as appropriate
		}
		
		public bool CanSaveAs(WarFoundryObject obj)
		{
			return CanSaveType(obj);
		}
		
		public bool CanSave(WarFoundryObject obj)
		{
			return savePaths.ContainsKey(obj);
		}
		
		public bool CanSaveType(WarFoundryObject obj)
		{
			return saveAsTypes.Contains(obj.GetType());
		}
	}
}