// (c) 2004 Electronic Arts Inc.
//

using System;
using System.IO;

namespace EA.GameTalkConfig
{
	/// <summary>
	/// Summary description for FileIO.
	/// </summary>
	public sealed class FileIO
	{
		/// <summary>
		/// Read the text content of a file
		/// </summary>
		/// <param name="fileName">The file to read the content from.</param>
		/// <returns>Return the content.</returns>
		public static string ReadFileContent(string fileName)
		{
			string content = string.Empty;
			StreamReader reader = null;
			try
			{
				if (!Path.IsPathRooted(fileName))
				{
					fileName = Path.Combine(Environment.CurrentDirectory, fileName);
				}

				reader = new StreamReader(fileName);
				content = reader.ReadToEnd();
			}
			catch
			{
			}
			finally
			{
				if (reader != null)
				{
					reader.Close();
				}
			}

			return content;
		}

		public static void UpdateFileContent(string fileName, string entry)
		{
			StreamWriter writer = null;
			try
			{
				string currentLogContent = string.Empty;

				if (!Path.IsPathRooted(fileName))
				{
					fileName = Path.Combine(Environment.CurrentDirectory, fileName);
				}
				string path = Path.GetDirectoryName(fileName);
				if (!Directory.Exists(path))
				{
					Directory.CreateDirectory(path);
				}
				else
				{
					currentLogContent = ReadFileContent(fileName);
					if (currentLogContent.Length > (65 * 1024))
					{
						currentLogContent = currentLogContent.Substring(0, (60 * 1024));
						currentLogContent += "\n\n... File truncated at this point ...\n";
					}
				}

				writer = new StreamWriter(fileName);
				writer.AutoFlush = true;
				writer.Write(entry);
				writer.Write(currentLogContent);
			}
			catch
			{
			}
			finally
			{
				if (writer != null)
				{
					writer.Flush();
					writer.Close();
				}
			}
		}

		public static void WriteFileContent(string fileName, string content)
		{
			StreamWriter writer = null;
			try
			{
				string currentLogContent = string.Empty;

				if (!Path.IsPathRooted(fileName))
				{
					fileName = Path.Combine(Environment.CurrentDirectory, fileName);
				}
				string path = Path.GetDirectoryName(fileName);
				if (!Directory.Exists(path))
				{
					Directory.CreateDirectory(path);
				}

				writer = new StreamWriter(fileName, false);
				writer.AutoFlush = true;
				writer.Write(content);
			}
			catch
			{
			}
			finally
			{
				if (writer != null)
				{
					writer.Flush();
					writer.Close();
				}
			}
		}
	}
}
