view api/Factories/Xml/WarFoundryXmlSaver.cs @ 0:520818033bb6

Initial commit of WarFoundry code
author IBBoard <dev@ibboard.co.uk>
date Fri, 19 Dec 2008 15:57:51 +0000
parents
children 306558904c2a
line wrap: on
line source

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());
		}
	}
}