view api/Factories/Xml/WarFoundryXmlSaver.cs @ 15:306558904c2a

Re #1 - LGPL license all code * Add LGPL header to all files * Add COPYING.LGPL and COPYING.GPL with content of license
author IBBoard <dev@ibboard.co.uk>
date Sun, 25 Jan 2009 14:50:36 +0000
parents 520818033bb6
children 3ea0ab04352b
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());
		}
	}
}