//  
//  Utils.cs
//  
//  Author:
//       Robert BRACCAGNI alias Gai-Luron <lfsgailuron@free.fr>
// 
//  Copyright (c) 2010 Gai-Luron
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
// 
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Collections;

namespace UTILS
{
    class utils
    {
        static Hashtable layoutlist = new Hashtable();
        public enum TrackCode
        {
            BL,	// 0
            SO,	// 1
            FE,	// 2
            AU,	// 3
            KY,	// 4
            WE,	// 5
            AS,	// 6
            RO, // 7
            LA, // 8
        };

        public enum LFSColor
        {
            Black,	// 0
            Red,	// 1
            Green,	// 2
            Yellow,	// 3
            Blue,	// 4
            Magenta,// 5
            Cyan,	// 6
            White,  // 7
            Gray,   // 8
        };

        static Random random = new Random();

        class infoTrack
        {
            public string shortName;
            public string groupName;
            public string extName;
            public string longName;
            public float length;
            public infoTrack(string shortName, string groupName, string longName, float length)
            {
                this.shortName = shortName;
                this.groupName = groupName;
                this.longName = longName;
                this.length = length;
                try
                {
                    this.extName = longName.Substring(groupName.Length + 1);
                }
                catch
                {
                    this.extName = longName;
                }
            }
        }
        static Hashtable trackList = new Hashtable();
        public static void initUtils()
        {
            initTrackList();
        }

        static public bool IsRunningOnMono()
        {
            return Type.GetType("Mono.Runtime") != null;
        }

        static void initTrackList()
        {
            string readLine;
            using (System.IO.StreamReader sr = new System.IO.StreamReader("trackList.cfg"))
            {
                while (!sr.EndOfStream)
                {
                    readLine = sr.ReadLine().Trim();
                    if (readLine != "")
                    {
                        string[] arg = readLine.Split(',');
                        trackList[arg[0].ToString()] = new infoTrack(arg[0].ToString(), arg[1], arg[2], float.Parse(arg[3]));
                    }
                }
            }

        }
        /// <summary>
        /// method for converting a System.DateTime value to a UNIX Timestamp
        /// </summary>
        /// <param name="value">date to convert</param>
        /// <returns></returns>
        static public double DateTimeToTimestamp(DateTime value)
        {
            //create Timespan by subtracting the value provided from
            //the Unix Epoch
            TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());

            //return the total seconds (which is a UNIX timestamp)
            return (double)span.TotalSeconds;
        }
        static public DateTime TimestampToDateTime(double timestamp)
        {
            DateTime converted = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            converted = converted.AddSeconds(timestamp);
            return converted;
        }
        static public bool existTrack(string track)
        {
            string cp = track.ToUpper();
            if (trackList.Contains(cp))
                return true;
            else
                return false;

        }
        static public float getLenTrack(string track)
        {
            string cp = track.ToUpper();
            if (trackList.Contains(cp))
                return (trackList[cp] as infoTrack).length;
            else
                return 0;
        }
        static public string getGroupTrack(string track)
        {
            string cp = track.ToUpper();
            if (trackList.Contains(cp))
                return (trackList[cp] as infoTrack).groupName;
            else
                return "Group Unknown";
        }
        static public string getExtTrack(string track)
        {
            string cp = track.ToUpper();
            if (trackList.Contains(cp))
                return (trackList[cp] as infoTrack).extName;
            else
                return "Ext Unknown";
        }

        static public string getLongTrackName(string track)
        {
            string retValue = "";
            string cp = track.ToUpper();
            string GetTrack = "";
            //Get last char of shorttrackname
            string GetShortNameTrack = track.Substring(cp.Length - 1, 1);

            //Read last char
            if ((GetShortNameTrack == "X") || (GetShortNameTrack == "R") || (GetShortNameTrack == "Y"))
                GetTrack = track.Substring(0, cp.Length - 1);
            else
                GetTrack = track.ToUpper();

            //Get track from the tracklist 
            if (trackList.Contains(GetTrack))
                retValue = (trackList[GetTrack] as infoTrack).longName;
            else
                retValue = "Track Unknown";

                //if lastchar contains X R or Y 
                if (GetShortNameTrack == "X")
                {
                    retValue = retValue + " Open";
                }
                else if (GetShortNameTrack == "R")
                {
                    retValue = retValue + " Reverse";
                }
                else if (GetShortNameTrack == "Y")
                {
                    retValue = retValue + " Open Reverse";
                }
            return (retValue);

        }

        public static void sendErrorMail(string email,string smtpServer, string loginMail, string passMail, string scripFileName, Exception ex)
        {
            if (email == "")
                return;

            MailMessage message = new MailMessage();

            message.From = new MailAddress("LFSLappernoreply@free.fr");
            message.To.Add(new MailAddress(email));
            message.Subject = "Error on Lapper instance using script file " + scripFileName;
            message.Body = ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace;

            SmtpClient client = new SmtpClient();
            client.Host = smtpServer;

            NetworkCredential mycred = new NetworkCredential(loginMail, passMail);

            client.Credentials = mycred;

            client.Send(message);
        }


		public static string quote(string str)
		{
			return "\"" + str + "\"";
		}

        public static string unquote(string str)
        {
            int l = str.Length;
            try
            {
                return str.Substring(1, l - 2);
            }
            catch
            {
                return "";
            }
        }

        //Replace CarGroups
        public static string replaceGroupCar(string cars)
        {
            cars = cars.Replace("TBO", "XRT+RB4+FXO");
            cars = cars.Replace("LRF", "LX6+RAC+FZ5");
            cars = cars.Replace("GTR", "FXR+XRR+FZR");
            return cars;
        }

        //Strip LFS Colors
        public static string stripLFSColor(string str)
        {
            string strStrip = str.Replace("^0", "").Replace("^1", "").Replace("^2", "").Replace("^3", "").Replace("^4", "").Replace("^5", "").Replace("^6", "").Replace("^7", "").Replace("^8", "").Replace("^9", "");
            return strStrip;
        }

        //Convert Special LFS Characters
        public static string ConvertSpecialChars(string str)
        { 
            string ConvertString = str.Replace("^v", "|").Replace("^a", "*").Replace("^c", ":").Replace("^d", "\\").Replace("^s", "/").Replace("^q", "?").Replace("^t", "\"").Replace("^l", "<").Replace("^r", ">").Replace("^^", "^");
            return ConvertString;
        }

        public static string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }

        static public string convTrack(string track)
        {
            string retValue = "";
            char LastChar;
			retValue = Enum.GetName(typeof(TrackCode), int.Parse(track[0].ToString()));
            //Trackcodes longer than 3 chars
            if (track.Length > 3)
            {
                LastChar = track[3];
                retValue += (int.Parse(track.Substring(1, 2)) + 1).ToString();
                LastChar = track[3];
            }
            else
            {
                retValue += (int.Parse(track[1].ToString()) + 1).ToString();
                LastChar = track[2];
            }
           
            if (LastChar == '1')
                retValue += "R";
            return retValue;
        }

        static public string convTrackShortnameToId(string track)
        {
            string retValue = "";
            int character;
            if (track.Length < 3)
            {
                retValue = "No code: " + track;
            }
            else
            {
                foreach (int val in Enum.GetValues(typeof(TrackCode)))
                {
                    if (Enum.GetName(typeof(TrackCode), val) == track.Substring(0, 2))
                    {
                        retValue = retValue += val.ToString();
                    }
                }
                retValue += (int.Parse(track[2].ToString()) - 1).ToString();

                if (track.Length > 4)
                    character = 4;
                else
                    character = 3;

                    if (track.Length > 3)
                    {
                        if (track[character] == 'R' || track[character] == 'Y') // 'Y' = open track, reverse
                            retValue += "1";
                        else
                            retValue += "0";    // 'X' = Open track
                    }
                    else
                    {
                        retValue += "0"; // Normal direction track if track length == 3
                    }
            }
            return retValue;
        }


        static public bool isNum(string val)
        {
            float myNum;

            try
            {
                myNum = float.Parse(val);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
