//  
//  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
    {
        public enum TrackCode
        {
            BL,	// 0
            SO,	// 1
            FE,	// 2
            AU,	// 3
            KY,	// 4
            WE,	// 5
            AS,	// 6
        };

        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 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], 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.Substring(0, 3).ToUpper();
            if (trackList.Contains(cp))
                return true;
            else
                return false;

        }
        static public float getLenTrack(string track)
        {
            string cp = track.Substring(0, 3).ToUpper();
            if (trackList.Contains(cp))
                return (trackList[cp] as infoTrack).length;
            else
                return 0;
        }
        static public string getGroupTrack(string track)
        {
            string cp = track.Substring(0, 3).ToUpper();
            if (trackList.Contains(cp))
                return (trackList[cp] as infoTrack).groupName;
            else
                return "Group UnkNown";
        }
        static public string getExtTrack(string track)
        {
            string cp = track.Substring(0, 3).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.Substring(0, 3).ToUpper();
            if (trackList.Contains(cp))
                retValue = (trackList[cp] as infoTrack).longName;
            else
                retValue = "Track UnkNown";

            if (track.Length > 3)
            {
                if (track.Substring(3, 1) == "X")
                {
                    retValue = retValue + " Open";
                }
                else if (track.Substring(3, 1) == "R")
                {
                    retValue = retValue + " Reverse";
                }
                else if (track.Substring(3, 1) == "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 "";
            }
        }
        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;
        }
        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;
        }
        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 = "";
			retValue = Enum.GetName(typeof(TrackCode), int.Parse(track[0].ToString()));
            retValue += (int.Parse(track[1].ToString()) + 1).ToString();
            if (track[2] == '1')
                retValue += "R";
            return retValue;
        }
        static public string convTrackShortnameToId(string track)
        {
            string retValue = "";
            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 > 3)
                {
                    if (track[3] == 'R' || track[3] == '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;
            }
        }
    }
}
