using System;
using System.Collections.Generic;
using System.Text;

namespace Machinations.FromFlash.utils
{
    public static class StringUtils
    {

		public static string GetCommand(string command)
		{
		    string result;
			int p = command.IndexOf('(');
			if (p >= 0) {
				result = command.Substring(0, p);
                command = command.Substring(0);
			} else {
				result = command;
				command = "";
			}
			return result;
		}
		
		public static string GetCondition(string word)
        {
			int i = 0;
			int depth  = 0;
			string result = "";
			while (i < word.Length)
            {
				char c = word[i];
				switch (c) {
					case '(':
						depth++;
						break;
					case ')':
						depth--;
						if (depth <= 0) {
							result += c;
							return result;
						}
						break;
				}
				i++;
				result += c;
			}
			return result;
		}
		
		public static List<string> GetParameters(string word){
			int i = 0;
			int depth  = 0;
			List<string> result = new List<string>();
		    string part = "";
			while (i < word.Length) {
				char c = word[i];
				switch (c) {
					case '(':
						depth++;
						if (depth == 1) {
							c = '\r';
						}
						break;
					case ',':
						if (depth == 1) {
							result.Add(part);
							part = "";
							c = '\r';
						}
						break;
					case ')':
						depth--;
						if (depth <= 0) {
							result.Add(part);
							return result;
						}
						break;
				}
				i++;
				if (c != '\r')part += c;
			}
			word = "";
			return result;
		}
		
		public static string FloatToStringMaxPrecision(double v, int maxDigits) 
		{
			double precision = Math.Pow(10, maxDigits);
			double f = Math.Floor(v* precision) / precision;
			string s = f.ToString();
			int p = s.IndexOf('.');
			if (p >= 0 && p<s.Length - maxDigits - 1) {
				s = s.Substring(0, p + maxDigits+1);
			}
			return s;
		}

        public static string SafeSubstring (this string s,int startIndex, int length)
        {
            if (startIndex + length >= s.Length )
            {
                return null;
            }
            return s.Substring(startIndex, length);
        }

    }
}
