//  
//  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 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 && track.Substring(3, 1) == "R")
                retValue = retValue + " 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 = "";
            switch (track[0])
            {
                case '0':
                    retValue = "BL";
                    break;
                case '1':
                    retValue = "SO";
                    break;
                case '2':
                    retValue = "FE";
                    break;
                case '3':
                    retValue = "AU";
                    break;
                case '4':
                    retValue = "KY";
                    break;
                case '5':
                    retValue = "WE";
                    break;
                case '6':
                    retValue = "AS";
                    break;
            }
            retValue += (int.Parse(track[1].ToString()) + 1).ToString();
            if (track[2] == '1')
                retValue += "R";
            return retValue;
        }

        bool isNum(string val)
        {
            float myNum;

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