view api/Factories/Xml/WarFoundryXmlSaver.cs @ 104:2f3cafb69799

Re #121: Migrate to AGPL license * Update all API files to AGPL license * Include AGPL license and remove GPL/LGPL documents * Fix copyright dates where they're known
author IBBoard <dev@ibboard.co.uk>
date Sat, 15 Aug 2009 10:36:50 +0000
parents 3ea0ab04352b
children f5aec697b8ea
line wrap: on
line source

// This file (WarFoundryXmlSaver.cs) is a part of the IBBoard.WarFoundry.API project and is copyright 2008, 2009 IBBoard.
//
// The file and the library/program it is in are licensed and distributed, without warranty, under the GNU Affero GPL license, either version 3 of the License or (at your option) any later version. Please see COPYING 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());
		}
	}
}