using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Text.RegularExpressions;

namespace com.deeperbeige.lib
{
	[InitializeOnLoad]
	public class AutoVersion
	{
	    private static string filename = "Assets/Deeperbeige/Resources/Version.txt";
		
	    static AutoVersion()
		{
	        EditorApplication.update += Init;
	    }
	
	    static void Init()
		{
	        EditorApplication.update -= Init;
	        AutoIncrementVersion();
	    }
	
	    static void AutoIncrementVersion()
		{
			string version = DateTime.Now.ToString() + "\n" +
			                 major + "." + minor + "." + revision.ToString("0000") + "\n" +
			                 PlayerSettings.bundleIdentifier;
			
            // Copy to resources
			File.WriteAllText(filename, version);
            AssetDatabase.Refresh();
	    }
		
		#region editor API - can use in build scripts etc
		
		public static int major
		{
			get
			{
				Match match = Regex.Match(PlayerSettings.bundleVersion, @"^(\d+)\.(\d+)$");
				if (match == null || ! match.Success)
				{
					Debug.LogWarning("Bundle version format incorrect (should be major.minor, eg \"1.0\")");
					return 0;
				}
				
				return int.Parse(match.Groups[1].Value);
			}
		}
		
		public static int minor
		{
			get
			{
				Match match = Regex.Match(PlayerSettings.bundleVersion, @"^(\d+)\.(\d+)$");
				if (match == null || ! match.Success)
				{
					Debug.LogWarning("Bundle version format incorrect (should be major.minor, eg \"1.0\")");
					return 0;
				}
				
				return int.Parse(match.Groups[2].Value);
			}
		}
		
		public static int revision
		{
			get
			{
				string version;
				try { version = File.ReadAllText(filename); }
				catch (FileNotFoundException)      { version = "0"; }
				catch (DirectoryNotFoundException) { version = "0"; }
				
				string[] lines = version.Split('\n');
				if (lines.Length != 3) return 0;
				
	            // Find revision, build time etc
				string[] parts = lines[1].Split('.');
				if (parts.Length == 0) parts = new string[] {"0"};
	            
				int revision;
				try { revision = int.Parse(parts[parts.Length - 1]) + 1; }
				catch (FormatException) { revision = 0; }
				
				return revision;
			}
		}
		
		#endregion
	}
}
