//  
//  cmdLapper.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 Configurator;
using System.Collections;

namespace LFSLapper
{
    partial class LFSClient
    {
        void Ver(int UCID)
        {
            try
            {
                SendMsgToConnection(UCID, "LFSLapper, Version=" + LFSLapper.getShortVersion(4) + " by Robert BRACCAGNI ( Gai-Luron )");
                SendMsgToConnection(UCID, "^3http://www.lfsforum.net/showthread.php?t=25756");
            }
            catch (System.Exception)
            {
                return;
            }
        }


        void closeTopGrip( ISMB.typExeFunc typ, infoPlayer currInfoPlayer,int click, string idButton )
        {
            closeTopGrip(currInfoPlayer);
        }
        void closeTopGrip(infoPlayer currInfoPlayer)
        {
            string[] par = new string[2];
            par[0] = "1";
            par[1] = "1";
            newCfg.executeFunction("__LapperCloseTop", currInfoPlayer, par);
        }

        void closeTopDrift(infoPlayer currInfoPlayer)
        {
            string[] par = new string[2];
            par[0] = "1";
            par[1] = "1";
            newCfg.executeFunction("__LapperCloseDrf", currInfoPlayer, par);
        }
        void closeToplfsWorldPB(infoPlayer currInfoPlayer)
        {
            string[] par = new string[2];
            par[0] = "1";
            par[1] = "1";
            newCfg.executeFunction("__LapperCloseLfsW", currInfoPlayer, par);
        }

        void closeTopStoredUser(infoPlayer currInfoPlayer)
        {
            string[] par = new string[2];
            par[0] = "1";
            par[1] = "1";
            newCfg.executeFunction("__LapperCloseUserTop", currInfoPlayer, par);
        }

        void closeAllTop(infoPlayer currPly)
        {
            closeTopGrip(currPly);
            closeTopDrift(currPly);
            closeTopStoredUser(currPly);
            closeToplfsWorldPB(currPly);
        }
        ArrayList GetListTopGrip(string username, string cmd, bool flagqual, bool flagNear)
		{
			string filtervalue = "";
			string relativeToUserName = "";


			string carName = newCfg.varsLapper.DefaultTopCar;

			int from = 1;
			if (flagNear)
				relativeToUserName = username;

			infoPlayer currPly = listOfPlayers.getPlayerByUserName(username);

			if (carName == "" && currPly.CName != "") // Set default car to current car if no default set in the lapper config
			{
				carName = currPly.CName;
			}
			closeAllTop(currPly);

			string[] splitCmd = cmd.Split(' ');
			for (int i = 0; i <= splitCmd.GetUpperBound(0); i++)
			{
				if (splitCmd[i].Trim() == "")
					continue;
				if (splitCmd[i] == "filter")
				{
					i++;
					try { filtervalue = splitCmd[i]; continue; }
					catch { filtervalue = ""; continue; }
				}
				// Find if car is present in line of command
				int j = 0;
				bool flagFind = false;
				foreach (string shortCarName in shortCarNames)
				{
					if (splitCmd[i].ToLower().IndexOf(shortCarName.ToLower()) != -1)
					{
						carName = splitCmd[i].ToUpper();
						flagFind = true;
						break;
					}
					j++;
				}
				if (flagFind)
					continue;
				// Find if offset
				try { from = int.Parse(splitCmd[i]); }
				catch (System.Exception) { }
			}
			from = from + 0;
			System.Collections.ArrayList list;
			if (flagqual)
				list = gripSqlDbs.GetTable2(from - 1, relativeToUserName, (int)paramLapper.nbLineTop, currState.ShortTrackName, carName, filtervalue, true, MaxGroupQual, MaxUserGroupQual, MinUserGroupQual);
			else
				list = gripSqlDbs.GetTable2(from - 1, relativeToUserName, (int)paramLapper.nbLineTop, currState.ShortTrackName, carName, filtervalue, false, 0, 0, 0);

			return list;
		}
        void TopGrip(string username,string cmd, bool flagqual, bool flagNear)
        {
			int decal = 0;
			int larg = 0;

			infoPlayer currPly = listOfPlayers.getPlayerByUserName( username );
			ArrayList list = GetListTopGrip( username, cmd, flagqual, flagNear );

			int currButt = 0;
            string colpos;
            string colcar;
            string colpb;
            string colgroup;
            string colnick;
            string colsplit;
            string cmdPlus = "";
            bool flagFirst = true;
            int P_L = 50;
            int P_H = 6;
            int P_T;
            string idButt;
            string userName;
            string nickName;

            if (flagqual)
            {
                P_L -= 4;
            }
            if (newCfg.varsLapper.LapTimeUsedForPb != 1)
                P_L -= 15;

            string idButtClose = "Close";
			currPly.playerBox.create(idButtClose, currPly.UCID, 87, 150, 25, 10, 10, -1, 0, 32, "", "Ok", "__LapperCloseTop");
//            currPly.playerBox.create(idButtClose, UCID, 87, 150, 25, 10, 10, -1, 0, 32, "", "Ok", (ISMB.executeButtonFunction)closeTopGrip);
            int initTop = 35;
            string butCloseAction = "&Close";
            string detailToDisplay = "__plusTop1";
            for (int i = 0; i >= 0 && i < (int)paramLapper.nbLineTop; i++)
            {

                if (i >= list.Count)
                {
                    userName = "";
                    nickName = "";
                    colpb = "";
                    colpos = "";
                    colnick = "";
                    colgroup = "";
                    colcar = "";
                    colsplit = "";
                }
                else
                {
                    userName = (list[i] as LFSDbs.gripDbs.DriverLapEntry).userName;
                    nickName = (list[i] as LFSDbs.gripDbs.DriverLapEntry).nickName;
                    string sGroup = "";
                    if ((list[i] as LFSDbs.gripDbs.DriverLapEntry).group != -1)
                    {
                        sGroup = ((char)((list[i] as LFSDbs.gripDbs.DriverLapEntry).group + 65)).ToString();
                    }
                    colpos = (list[i] as LFSDbs.gripDbs.DriverLapEntry).pos.ToString();
                    if ((list[i] as LFSDbs.gripDbs.DriverLapEntry).personalBestLapTime > (3600000 - 1000))
                    {
                        colpb = ((3600000 - ((list[i] as LFSDbs.gripDbs.DriverLapEntry).personalBestLapTime)) / 10).ToString()
                                + "/" + newCfg.varsLapper.LapTimeUsedForPb.ToString() + lfsLang.replaceLangStr( currPly.idLang, "%{built_lapsdone}%" );
                        colpos = "-";
                    }
                    else
                    {
                        colpb = unitConv.LongToHMS((list[i] as LFSDbs.gripDbs.DriverLapEntry).personalBestLapTime);
                    }
                    colnick = nickName;
                    colgroup = sGroup;
                    colcar = (list[i] as LFSDbs.gripDbs.DriverLapEntry).carName;



                    colsplit = "";
                    for (int k = 0; k < 3; k++)
                    {
                        long SplitTime = (list[i] as LFSDbs.gripDbs.DriverLapEntry).splitTime[k];

                        //only show split time if it is not zero
                        if (SplitTime != 0)
                        {
                            colsplit += " ";
                            colsplit += unitConv.LongToHMS(SplitTime);
                        }
                    }

                }
                int bStyle = 32;
                if (username.ToLower() == userName.ToLower())
                {
                    bStyle = 16;
                }

                string lid;
                if (flagFirst)
                {
                    decal = 0;
                    flagFirst = false;
                    P_T = initTop + (P_H * currButt);
                    idButt = "Drf" + currButt.ToString();

                    larg = 10;
                    lid = idButt + "colpos";
					currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_pos}%"));
					currPly.playerBox.show(lid, currPly.UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    if (flagqual)
                    {
                        larg = 8;
                        lid = idButt + "colgroup";
						currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_grp}%"));
						currPly.playerBox.show(lid, currPly.UCID);
                        butCloseAction += "&" + lid;
                        decal += larg;
                    }

                    larg = 10;
                    lid = idButt + "colcar";
					currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_car}%"));
					currPly.playerBox.show(lid, currPly.UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;


                    larg = 40;
                    lid = idButt + "colnick";
					currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_nick}%"));
					currPly.playerBox.show(lid, currPly.UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    larg = 15;
                    lid = idButt + "colpb";
					currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_pb}%"));
					currPly.playerBox.show(lid, currPly.UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    larg = 25;
                    lid = idButt + "colsplit";
					currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_splits}%"));
					currPly.playerBox.show(lid, currPly.UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    currButt++;
                }
                P_T = initTop + (P_H * currButt);
                idButt = "Top" + currButt.ToString();
                decal = 0;
                larg = 0;
                lid = idButt + "colpos";

                larg = 10;
				currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 6, "", colpos);
				currPly.playerBox.show(lid, currPly.UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                if (flagqual)
                {
                    larg = 8;
                    lid = idButt + "colgroup";
					currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle, "", " " + colgroup);
					currPly.playerBox.show(lid, currPly.UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;
                }

                larg = 10;
                lid = idButt + "colcar";
				currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle, "", colcar);
				currPly.playerBox.show(lid, currPly.UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                larg = 40;
                lid = idButt + "colnick";
				currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 64, "", colnick);
				currPly.playerBox.show(lid, currPly.UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                larg = 15;
                lid = idButt + "colpb";
				currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, 15, P_H, P_H, -1, 0, bStyle, "", colpb);
				currPly.playerBox.show(lid, currPly.UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                larg = 25;
                lid = idButt + "colsplit";
				currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, 25, P_H, P_H, -1, 0, bStyle, "", colsplit);
				currPly.playerBox.show(lid, currPly.UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                if (newCfg.varsLapper.LapTimeUsedForPb != 1 && userName != "")
                {

                    larg = 5;
                    lid = idButt + "colplus";
					currPly.playerBox.create(lid, currPly.UCID, P_L + decal, P_T, 5, P_H, P_H, -1, 0, bStyle, "", "+", "__plus" + idButt, null);
					currPly.playerBox.show(lid, currPly.UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    larg = 25;
                    cmdPlus = "closePrivButton(\"cmdPlus0&cmdPlus1&cmdPlus2&cmdPlus3&cmdPlus4&cmdPlus5&cmdPlus6&cmdPlus7&cmdPlus8&cmdPlus9&cmdPlus10\");";
                    butCloseAction += "&cmdPlus0&cmdPlus1&cmdPlus2&cmdPlus3&cmdPlus4&cmdPlus5&cmdPlus6&cmdPlus7&cmdPlus8&cmdPlus9&cmdPlus10";
                    cmdPlus += "openPrivButton( \"cmdPlus10\""
                                + "," + (P_L + decal + 5).ToString()
                                + "," + (initTop).ToString()
                                + "," + larg.ToString()
                                + "," + P_H.ToString()
                                + "," + P_H.ToString()
                                + ",-1,32"
                                + ",\"" + colnick + "\""
                                + ",\"\"); ";
                    for (int j = 0; j < (list[i] as LFSDbs.gripDbs.DriverLapEntry).listPB.Count; j++)
                    {
                        cmdPlus += "openPrivButton( \"cmdPlus" + j.ToString() + "\""
                                    + "," + (P_L + decal + 5).ToString()
                                    + "," + (initTop + ((j + 1) * P_H)).ToString()
                                    + "," + larg.ToString()
                                    + "," + P_H.ToString()
                                    + "," + P_H.ToString()
                                    + ",-1,32"
                                    + ",\"" + unitConv.LongToHMS(((list[i] as LFSDbs.gripDbs.DriverLapEntry).listPB[j] as LFSDbs.gripDbs.PbLapEntry).personalBestLapTime) + "\""
                                    + ",\"\"); ";
                        if (j + 1 >= newCfg.varsLapper.LapTimeUsedForPb)
                            break;
                    }
                    decal += larg;
                    string idcmd = "__plus" + idButt;
                    string[] parg = "$arg,$id".Split(',');
                    currPly.functionsLapper[idcmd] = new GLScript.GLApp.functionDef(parg, 2, new GLScript.TokenBuffer(cmdPlus, "", 0,null,null), 0);
                    if (idButt == "Top1" || userName == username)
                    {
                        detailToDisplay = idcmd;
                    }
                }


                //                Console.WriteLine(cmdPlus);

                currButt++;
                //                SendMsgToConnection(UCID, sb.ToString());
            }
            string[] pparg = "$arg,$id".Split(',');
            newCfg.executeFunction(detailToDisplay, currPly, pparg);
            currPly.playerBox.UpdateLT(idButtClose, (decal) / 2 + P_L - 12, initTop + 2 + (P_H * currButt));
            newCfg.addFunction("__LapperCloseTop", "closePrivButton(\"" + butCloseAction.Substring(1) + "\");", "$keyFlags,$id");
			currPly.playerBox.show(idButtClose, currPly.UCID);
            //            Console.WriteLine(DateTime.Now.ToString() + " : End button Top list");


        }
        
        void TopDrift(int UCID, string username, string nickname, string cmd, bool flagQual, bool flagNear)
        {

            string playerNameToSend = nickname;
            string filtervalue = "";
            string relativeToUserName = "";
            int decal = 0;
            int larg = 0;



            string carName = newCfg.varsLapper.DefaultTopCar;

            int from = 1;
            if (flagNear)
                relativeToUserName = username;

            infoPlayer currPly = listOfPlayers.getPlayerByUCID(UCID);

            if (carName == "" && currPly.CName != "") // Set default car to current car if no default set in the lapper config
            {
                carName = currPly.CName;
            }

            closeAllTop(currPly);



            string[] splitCmd = cmd.Split(' ');
            for (int i = 0; i <= splitCmd.GetUpperBound(0); i++)
            {
                if (splitCmd[i].Trim() == "")
                    continue;
                // find if filter is present
                if (splitCmd[i] == "filter")
                {
                    i++;
                    try { filtervalue = splitCmd[i]; continue; }
                    catch { filtervalue = ""; continue; }
                }
                // Find if car is present in line of command
                int j = 0;
                bool flagFind = false;
                foreach (string shortCarName in shortCarNames)
                {
                    if (splitCmd[i].IndexOf(shortCarName.ToLower()) != -1)
                    {
                        //                        carName = (string)shortCarNames[j];
                        carName = splitCmd[i].ToUpper();
                        flagFind = true;
                        break;
                    }
                    j++;
                }
                if (flagFind)
                    continue;
                // Find if offset
                try { from = int.Parse(splitCmd[i]); }
                catch (System.Exception) { }
            }
            from = from + 0;
            System.Collections.ArrayList list;
            if (flagQual)
                list = driftSqlDbs.GetTable(from - 1, relativeToUserName, (int)paramLapper.nbLineTop, currState.ShortTrackName, carName, filtervalue, true, MaxGroupQual, MaxUserGroupQual, MinUserGroupQual);
            else
                list = driftSqlDbs.GetTable(from - 1, relativeToUserName, (int)paramLapper.nbLineTop, currState.ShortTrackName, carName, filtervalue, false, 0, 0, 0);

            int currButt = 0;
            string colpos;
            string colcar;
            string colDriftPoints;
            string colgroup;
            string colnick;
            bool flagFirst = true;
            int P_L = 63;
            int P_H = 6;
            int P_T;
            string idButt;
            string userName;
            string nickName;

            if (flagQual)
            {
                P_L -= 4;
            }

            //            Console.WriteLine(DateTime.Now.ToString() + " : Start button Top list");
            string idButtClose = "Close";
            currPly.playerBox.create(idButtClose, UCID, 87, 150, 25, 10, 10, -1, 0, 32 , "", "Ok", "__LapperCloseDrf",null);
            int initTop = 35;
            string butCloseAction = "&Close";
            for (int i = 0; i >= 0 && i < (int)paramLapper.nbLineTop; i++)
            {



                string sGroup = "";
                if (i >= list.Count)
                {
                    userName = "";
                    nickName = "";
                    sGroup = "";
                    colpos = "";
                    colnick = "";
                    colgroup = "";
                    colcar = "";
                    colDriftPoints = "";
                }
                else
                {
                    userName = (list[i] as LFSDbs.driftDbs.DriverLapEntry).userName;
                    nickName = (list[i] as LFSDbs.driftDbs.DriverLapEntry).nickName;
                    if ((list[i] as LFSDbs.driftDbs.DriverLapEntry).group != -1)
                    {
                        sGroup = ((char)((list[i] as LFSDbs.driftDbs.DriverLapEntry).group + 65)).ToString();
                    }
                    colpos = (list[i] as LFSDbs.driftDbs.DriverLapEntry).pos.ToString();
                    colDriftPoints = (list[i] as LFSDbs.driftDbs.DriverLapEntry).driftPoints.ToString();
                    colnick = nickName;
                    colgroup = sGroup;
                    colcar = (list[i] as LFSDbs.driftDbs.DriverLapEntry).carName;
                }
                string lid;
                int bStyle = 32;
                if (username.ToLower() == userName.ToLower())
                {
                    bStyle = 16;
                }

                if (flagFirst)
                {
                    decal = 0;
                    flagFirst = false;
                    P_T = initTop + (P_H * currButt);
                    idButt = "Top" + currButt.ToString();

                    larg = 10;
                    lid = idButt + "colpos";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_pos}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    if (flagQual)
                    {
                        larg = 8;
                        lid = idButt + "colgroup";
                        currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_grp}%"));
                        currPly.playerBox.show(lid, UCID);
                        butCloseAction += "&" + lid;
                        decal += larg;
                    }

                    larg = 10;
                    lid = idButt + "colcar";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_car}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;


                    larg = 40;
                    lid = idButt + "colnick";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_nick}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    larg = 15;
                    lid = idButt + "coldriftpoints";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr( currPly.idLang, "%{built_points}%" ));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    currButt++;
                }
                P_T = initTop + (P_H * currButt);
                idButt = "Top" + currButt.ToString();
                decal = 0;
                larg = 0;
                lid = idButt + "colpos";

                larg = 10;
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 6, "", colpos);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                if (flagQual)
                {
                    larg = 8;
                    lid = idButt + "colgroup";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle, "", " " + colgroup);
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;
                }

                larg = 10;
                lid = idButt + "colcar";
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle, "", colcar);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                larg = 40;
                lid = idButt + "colnick";
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 64, "", colnick);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                larg = 15;
                lid = idButt + "coldriftpoint";
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, 15, P_H, P_H, -1, 0, bStyle, "", colDriftPoints);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                currButt++;
            }
            currPly.playerBox.UpdateLT(idButtClose, (decal) / 2 + P_L - 12, initTop + 2 + (P_H * currButt));
            newCfg.addFunction("__LapperCloseDrf", "closePrivButton(\"" + butCloseAction.Substring(1) + "\");", "$keyFlags,$id");
            currPly.playerBox.show(idButtClose, UCID);
        }

        void lfsWorldPB(int UCID, string pusername, string pnickname, string pcmd, int from )
        {

            int decal = 0;
            int larg = 0;

            string carName = "";
            string trackName = "";

            infoPlayer currPly = listOfPlayers.getPlayerByUCID(UCID);

            if( from == 0 )
                closeAllTop(currPly);


            string[] splitCmd = pcmd.Split(' ');
            for (int i = 0; i <= splitCmd.GetUpperBound(0); i++)
            {
                if (splitCmd[i].Trim() == "")
                    continue;
                foreach (string shortCarName in shortCarNames)
                {
                    if (splitCmd[i].ToLower().IndexOf(shortCarName.ToLower()) != -1)
                    {
                        carName = splitCmd[i].ToUpper();
                        break;
                    }
                }
                if( UTILS.utils.existTrack( splitCmd[i] ) )
                    trackName = splitCmd[i].ToUpper();
            }

            System.Collections.ArrayList list = currPly.getUserListPb( carName, trackName);
            if (list == null)
            {
                SendMsgToConnection(UCID, lfsLang.replaceLangStr( currPly.idLang, "%{built_nolfspb}%" ));
                return;
            }
            if (list.Count == 0)
            {
                SendMsgToConnection(UCID, lfsLang.replaceLangStr( currPly.idLang, "%{built_nolfspbcrit}%" ));
                return;
            }
            int currButt = 0;
            string colnick;
            string colcar;
            string coltrack;
            string colSplit1;
            string colSplit2;
            string colSplit3;
            string colLapTime;
            string colSplits;
            bool flagFirst = true;
            int P_L = 63;
            int P_H = 6;
            int P_T;
            string idButt;


            //            Console.WriteLine(DateTime.Now.ToString() + " : Start button Top list");
            string idButtClose = "Close";
            currPly.playerBox.create(idButtClose, UCID, 87, 150, 25, 10, 10, -1, 0, 32 , "", "Ok", "__LapperCloseLfsW");
            string idButtNext = "Next";
            currPly.playerBox.create(idButtNext, UCID, 102, 150, 25, 10, 10, -1, 0, 32 , "", " > ", "__LapperNextLfsW");
            string idButtPrevious = "Previous";
            currPly.playerBox.create(idButtPrevious, UCID, 63, 150, 25, 10, 10, -1, 0, 32 , "", " < ", "__LapperPreviousLfsW");
            int initTop = 35;
            string butCloseAction = "&Close&Next&Previous";
            int nextFrom = (int)paramLapper.nbLineTop + from;
            int previousFrom = from - (int)paramLapper.nbLineTop;
            for (int i = from; i >= 0 && i < (int)paramLapper.nbLineTop + from; i++)
            {

                if (i >= list.Count)
                {
                    nextFrom = -1;
                    colnick = "";
                    colcar = "";
                    coltrack = "";
                    colSplit1 = "";
                    colSplit2 = "";
                    colSplit3 = "";
                    colLapTime = "";
                    colSplits = "";
                }
                else
                {
					LapperThreads.PubStatUser.PubStatUserPb.PbElem elem = (LapperThreads.PubStatUser.PubStatUserPb.PbElem)list[i];

                    if (elem.lapTime == 0)
                        continue;
                    colnick = pnickname;
					colcar = elem.car;
                    coltrack = elem.track;
                    colSplit1 = "";
                    colSplit2 = "";
                    colSplit3 = "";
                    if( elem.split1 != 0 )
                        colSplit1 = unitConv.LongToHMS(elem.split1);
                    if (elem.split2 != 0)
                        colSplit2 = unitConv.LongToHMS(elem.split2);
                    if (elem.split3 != 0)
                        colSplit3 = unitConv.LongToHMS(elem.split3);
                    colLapTime = unitConv.LongToHMS(elem.lapTime );
                    colSplits = colSplit1;
                    if (colSplit2 != "")
                        colSplits = colSplits + " / " + colSplit2;
                    if (colSplit3 != "")
                        colSplits = colSplits + " / " + colSplit3;
                }
                string lid;
                int bStyle = 32;
                if (flagFirst)
                {
                    decal = 0;
                    flagFirst = false;
                    P_T = initTop + (P_H * currButt);
                    idButt = "Top" + currButt.ToString();

                    P_T = initTop + (P_H * currButt);
                    larg = 75;
                    lid = idButt + "title";
                    string title = "LFS World PB for " + pnickname;
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T - 5, larg, P_H + 5 , P_H, -1, 0, bStyle + 1, "", title);
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    currButt++;

                    P_T = initTop + (P_H * currButt);


                    larg = 10;
                    lid = idButt + "colcar";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_car}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    larg = 10;
                    lid = idButt + "coltrack";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_track}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;


                    larg = 40;
                    lid = idButt + "colsplit";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_splits}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    larg = 15;
                    lid = idButt + "collaptime";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_pb}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    currButt++;
                }
                P_T = initTop + (P_H * currButt);
                idButt = "Top" + currButt.ToString();
                decal = 0;
                larg = 0;
                lid = idButt + "colcar";

                larg = 10;
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 6, "", colcar);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;


                larg = 10;
                lid = idButt + "coltrack";
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle, "", coltrack);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                larg = 40;
                lid = idButt + "colsplit";
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle, "", colSplits);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;


                larg = 15;
                lid = idButt + "collaptime";
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, 15, P_H, P_H, -1, 0, bStyle, "", colLapTime);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                currButt++;
            }
            currPly.playerBox.UpdateLT(idButtClose, (decal) / 2 + P_L - 12, initTop + 2 + (P_H * currButt));
            newCfg.addFunction("__LapperCloseLfsW", "closePrivButton(\"" + butCloseAction.Substring(1) + "\");", "$keyFlags,$id");

            currPly.playerBox.UpdateLT(idButtNext, (decal) / 2 + P_L + 13 , initTop + 2 + (P_H * currButt));
            newCfg.addFunction("__LapperNextLfsW", "CurrentPlayerlfsWorldPBFrom( \"" + pcmd + "\"," + nextFrom + " );", "$keyFlags,$id");

            currPly.playerBox.UpdateLT(idButtPrevious, (decal) / 2 + P_L - 12 - 25, initTop + 2 + (P_H * currButt));
            newCfg.addFunction("__LapperPreviousLfsW", "CurrentPlayerlfsWorldPBFrom( \"" + pcmd + "\"," + previousFrom + " );", "$keyFlags,$id");
            
            currPly.playerBox.show(idButtClose, UCID);
            if (nextFrom != -1)
                currPly.playerBox.show(idButtNext, UCID);
            if (previousFrom >= 0)
                currPly.playerBox.show(idButtPrevious, UCID);
        }
        void TopStoredUser(int UCID, string title, string key, string pusername, string pnickname, string pcmd,  bool flagNear, bool flagDesc)
        {

            string playerNameToSend = pnickname;
            string filtervalue = "";
            string relativeToUserName = "";
            int decal = 0;
            int larg = 0;
            string strTmp = "";




            int from = 1;
            if (flagNear)
                relativeToUserName = pusername;

            infoPlayer currPly = listOfPlayers.getPlayerByUCID(UCID);

            closeAllTop(currPly);



            string[] splitCmd = pcmd.Split(' ');
            for (int i = 0; i <= splitCmd.GetUpperBound(0); i++)
            {
                if (splitCmd[i].Trim() == "")
                    continue;
                // find if filter is present
                if (splitCmd[i] == "filter")
                {
                    i++;
                    try { filtervalue = splitCmd[i]; continue; }
                    catch { filtervalue = ""; continue; }
                }
                // Find if offset
                try { from = int.Parse(splitCmd[i]); }
                catch (System.Exception) { }
            }
            from = from + 0;
            System.Collections.ArrayList list;

            list = storedSqlDbs.GetTable(key, from - 1, relativeToUserName, (int)paramLapper.nbLineTop, filtervalue, flagDesc);

            int currButt = 0;
            string colpos;
            int numVal;
            string colnick;
            bool flagFirst = true;
            int P_L = 68;
            int P_H = 6;
            int P_T;
            string idButt;
            string userName;
            string nickName;


            //            Console.WriteLine(DateTime.Now.ToString() + " : Start button Top list");
            string idButtClose = "Close";
            currPly.playerBox.create(idButtClose, UCID, 87, 150, 25, 10, 10, -1, 0, 32 , "", "Ok", "__LapperCloseUserTop");
            int initTop = 35;
            string butCloseAction = "&Close";
            for (int i = 0; i >= 0 && i < (int)paramLapper.nbLineTop; i++)
            {



                if (i >= list.Count)
                {
                    userName = "";
                    nickName = "";
                    colpos = "";
                    colnick = "";
                    numVal = 0;
                }
                else
                {
                    userName = (list[i] as LFSDbs.storedDbs.DriverLapEntry).userName;
                    nickName = (list[i] as LFSDbs.storedDbs.DriverLapEntry).nickName;
                    colpos = (list[i] as LFSDbs.storedDbs.DriverLapEntry).pos.ToString();
                    numVal = (list[i] as LFSDbs.storedDbs.DriverLapEntry).sumNumVal;
                    colnick = nickName;
                }
                string lid;
                int bStyle = 32;
                if (pusername.ToLower() == userName.ToLower())
                {
                    bStyle = 16;
                }

                if (flagFirst)
                {
                    decal = 0;
                    flagFirst = false;
                    P_T = initTop + (P_H * currButt);
                    idButt = "TopUser" + currButt.ToString();

                    P_T = initTop + (P_H * currButt);
                    larg = 65;
                    lid = idButt + "title";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", title);
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    currButt++;

                    P_T = initTop + (P_H * currButt);
                    decal = 0;

                    larg = 10;
                    lid = idButt + "colpos";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_pos}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;


                    larg = 40;
                    lid = idButt + "colnick";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_nick}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    larg = 15;
                    lid = idButt + "colUserValue";
                    currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 1, "", lfsLang.replaceLangStr(currPly.idLang, "%{built_points}%"));
                    currPly.playerBox.show(lid, UCID);
                    butCloseAction += "&" + lid;
                    decal += larg;

                    currButt++;
                }
                P_T = initTop + (P_H * currButt);
                idButt = "TopUser" + currButt.ToString();
                decal = 0;
                larg = 0;
                lid = idButt + "colpos";

                larg = 10;
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 6, "", colpos);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;


                larg = 40;
                lid = idButt + "colnick";
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, larg, P_H, P_H, -1, 0, bStyle + 64, "", colnick);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                larg = 15;
                lid = idButt + "colUserValue";
                if (numVal == 0)
                    strTmp = "";
                else
                    strTmp = numVal.ToString();
                currPly.playerBox.create(lid, UCID, P_L + decal, P_T, 15, P_H, P_H, -1, 0, bStyle, "", strTmp);
                currPly.playerBox.show(lid, UCID);
                butCloseAction += "&" + lid;
                decal += larg;

                currButt++;
            }
            currPly.playerBox.UpdateLT(idButtClose, (decal) / 2 + P_L - 12, initTop + 2 + (P_H * currButt));
            newCfg.addFunction("__LapperCloseUserTop", "closePrivButton(\"" + butCloseAction.Substring(1) + "\");", "$keyFlags,$id");
            currPly.playerBox.show(idButtClose, UCID);
        }

        void ShowHand(infoPlayer currInfoPlayer, string cmd)
        {
            string searchUserName = "";
            string dispName = "";

            searchUserName = searchUserName = cmd;
            dispName = searchUserName;
            if (searchUserName == "")
            {
                searchUserName = currInfoPlayer.userName;
                dispName = currInfoPlayer.nickName;
            }

            int H_Mass = 0;
            int H_TRes = 0;
// Search handicap for a player
// Priority level low to high -> Car, Car/Track, Player
            //Car Handicap
            try
            {
                H_Mass = (carHandicap[currInfoPlayer.CName.ToLower()] as infoHandicap).H_Mass;
                H_TRes = (carHandicap[currInfoPlayer.CName.ToLower()] as infoHandicap).H_TRes;
            }
            catch { }
            // Car/Track Handicap
            try
            {
                string carTrack = currInfoPlayer.CName.ToLower() + "/" + currState.ShortTrackName.ToLower();
                H_Mass = (carTrackHandicap[carTrack] as infoHandicap).H_Mass;
                H_TRes = (carTrackHandicap[carTrack] as infoHandicap).H_TRes;
            }
            catch { }
            //Player Handicap
            try
            {
                H_Mass = (playerHandicap[searchUserName.ToLower()] as infoHandicap).H_Mass;
                H_TRes = (playerHandicap[searchUserName.ToLower()] as infoHandicap).H_TRes;
            }
            catch { }
            lfsLang.doParmsTranslation(currInfoPlayer.idLang, "%{built_hand_nick}%", dispName);
            SendMsgToConnection(currInfoPlayer.UCID,
                            lfsLang.doParmsTranslation(currInfoPlayer.idLang, "%{built_hand_nick}%", dispName)
            );
            if (searchUserName == currInfoPlayer.userName)
            {
                SendMsgToConnection(currInfoPlayer.UCID,
                            lfsLang.doParmsTranslation(currInfoPlayer.idLang, "%{built_hand_curr}%", currInfoPlayer.P_Mass.ToString(),currInfoPlayer.P_TRes.ToString() )
                );
            }
            SendMsgToConnection(currInfoPlayer.UCID,
                            lfsLang.doParmsTranslation(currInfoPlayer.idLang, "%{built_hand_req}%", dispName, H_Mass.ToString(),H_TRes.ToString() )
            );

        }
        void ShowStats(int UCID, string pusername, string nickname, string cmd, bool flagqual)
        {
            string searchName = "";
            string playerNameToSend = nickname;

            // get parameter of command

            searchName = cmd;

            if (searchName.Trim() == "")
                searchName = UTILS.utils.stripLFSColor( nickname );
            try
            {
                System.Collections.ArrayList cars = gripSqlDbs.GetCars(currState.ShortTrackName);

                foreach (string carName in cars)
                {
                    System.Collections.ArrayList list;
                    list = gripSqlDbs.GetTable2(0, pusername, 15, currState.ShortTrackName, carName, "", flagqual, MaxGroupQual, MaxUserGroupQual, MinUserGroupQual);
                    foreach (LFSDbs.gripDbs.DriverLapEntry de in list)
                    {
                        if (de.userName == pusername)
                        {
                            string userName = de.userName;
                            string nickName = de.nickName;
                            SendMsgToConnection(UCID, string.Format("{3}/{4}. {0}^8 {1} {2}",
                                                                    nickName,
                                                                    unitConv.LongToHMS(de.personalBestLapTime),
                                                                    carName,
                                                                    de.pos,
                                                                    de.total
                            ));
                            string sb = "";

                            for (int k = 0; k < 3; k++)
                            {
                                long SplitTime = de.splitTime[k];

                                //only show split time if it is not zero
                                if (SplitTime != 0)
                                {
                                    sb = sb + " " + unitConv.LongToHMS(SplitTime);
                                }
                            }
                            SendMsgToConnection(UCID, sb);
                        }
                    }

                }
            }
            catch (System.Exception)
            {
                return;
            }
        }
        public posQualUser getPosQual( string userName, bool flagqual)
        {
            System.Collections.ArrayList list;
            int findPosition = -1;
            int nb = -1;
            string findUserName = "";
            string findNickName = "";
            int findGroup = -1;
            string carName;
            carName = newCfg.varsLapper.DefaultTopCar;

            list = gripSqlDbs.GetTable2( 0,userName,20,currState.ShortTrackName, carName,"",flagqual, MaxGroupQual, MaxUserGroupQual, MinUserGroupQual);
            foreach (LFSDbs.gripDbs.DriverLapEntry de in list)
            {
                if( de.userName == userName.ToLower() ){
                    findPosition = de.pos;
                    findUserName = de.userName;
                    findNickName = de.nickName;
                    findGroup = de.group;
                    nb = de.total;
                    break;
                }
            }
            if (findPosition == -1) 
                return new posQualUser("", "", 0, 0, -1);

            return new posQualUser(findUserName, findNickName, findPosition , nb, findGroup);
        }
        public posQualUser getPosQualDrift(string userName, string nickName, string cmd, bool flagqual)
        {

            string searchName = "";
            if (cmd.Trim() == "")
                searchName = UTILS.utils.stripLFSColor(nickName);
            else
                searchName = cmd;

            string playerNameToSend = nickName;
            try
            {
                string carName;
                carName = newCfg.varsLapper.DefaultTopCar;
                System.Collections.ArrayList list;

                list = driftSqlDbs.GetTable(0,userName,20, currState.ShortTrackName, carName, "", flagqual, MaxGroupQual, MaxUserGroupQual, MinUserGroupQual);

                string findUserName = "";
                string findNickName = "";
                int findPosition = -1;
                int tmppos = 0;
                int nb = list.Count;
                foreach (LFSDbs.driftDbs.DriverLapEntry de in list)
                {
                    if (UTILS.utils.stripLFSColor(de.nickName).ToLower().IndexOf(searchName.ToLower()) != -1)
                    {
                        if (!playerFilter.ContainsKey(de.userName.ToLower()) && flagqual)
                            break;
                        findPosition = tmppos;
                        findUserName = de.userName;
                        findNickName = de.nickName;
                        break;
                    }
                    else tmppos++;
                }
                if (findPosition == -1) return new posQualUser("", "", 0, 0, -1);


                return new posQualUser(findUserName, findNickName, findPosition + 1, nb, (list[findPosition] as LFSDbs.gripDbs.DriverLapEntry).group);
            }
            catch (System.Exception)
            {
                return new posQualUser("","",0, 0, -1);
            }
        }

        void ShowDriftStats(int UCID, string pusername, string nickname, string cmd,bool flagqual)
        {

            string searchName = "";
            string playerNameToSend = nickname;

            // get parameter of command

            searchName = cmd;

            if (searchName.Trim() == "")
                searchName = UTILS.utils.stripLFSColor(nickname);
            try
            {
                System.Collections.ArrayList cars = driftSqlDbs.GetCars(currState.ShortTrackName);

                foreach (string carName in cars)
                {
                    System.Collections.ArrayList list;

                    list = driftSqlDbs.GetTable(0,pusername,15,currState.ShortTrackName, carName, "", flagqual, MaxGroupQual, MaxUserGroupQual, MinUserGroupQual);

                    int position = -1;
                    int nb = list.Count;
                    foreach (LFSDbs.driftDbs.DriverLapEntry de in list)
                    {
                        if (de.userName == pusername)
                        {
                            string userName = de.userName;
                            string nickName = de.nickName;
                            SendMsgToConnection(UCID, string.Format("{3}. {0}^8 {1} {2}",
                                                nickName,
                                                (list[position] as LFSDbs.driftDbs.DriverLapEntry).driftPoints,
                                                carName,
                                                de.pos
                                                )

                            );
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                return;
            }

        }

    }
}