#include <qapplication.h>
#include <cstdlib>
//#include "libmyth/mythdialogs.h"
#include "libmyth/mythcontext.h"
#include "libmyth/settings.h"
#include "libmyth/langsettings.h"
#include "libmyth/mythdbcon.h"
#include <libmyth/exitcodes.h>
#include "libmythtv/tv.h"
#include "installdialog.h"
#include "installsettings.h"
#include "password_manage.h"
#include "autocard.h"
#include "settemplate.h"
#include "mythdialogbox.h"
//#include "mv_common.h"

#include <iostream>
#include <fstream>
#include <stdio.h>

#include "libmyth/dialogbox.h"
#include <qlist.h>
#include <qvaluevector.h>
#include <qdir.h>
HostParms hostparm;
DDCinfo ddcinfo;


void initKeys(void)
{
    REG_KEY("Welcome", "STARTXTERM", "Open an Xterm window", "F12");
    REG_KEY("Welcome", "SHOWSETTINGS", "Show Mythshutdown settings", "F11");
}


int main(int argc, char **argv)
{
    bool bShowSettings = false;
    bool bShowNetwork = false;
    bool bShowHostype = false;
    bool bShowMisc = false;
    bool bShowshutdown = false;
    bool bShowadvanced = false;
    bool bShowsound = false;
    bool bShowadvancedX = false;
    bool bShowAccesscontrol = false;
    bool bShowplugins = false;
    bool bShowTemplate = false;
    bool bShowuser  = false;
    bool bShowwebuser = false;
    bool bRunSetup = false;
    bool bShowHelp = false;
    bool bShowReadme = false;
    bool bShowddns = false;
    bool bShowinfrared = false;
    bool bShowscreensaver = false;

    QStringList template_c_line  ;
    QString modulelist = "" ;
    QString templateop="";
    QString templatename="";
    QString templatehostname="";
    QApplication a(argc, argv);

    gContext = NULL;
    gContext = new MythContext(MYTH_BINARY_VERSION);
    if (!gContext->Init())
    {
        VERBOSE(VB_IMPORTANT, "mythwelcome: Could not initialize myth context. "
                        "Exiting.");
        return FRONTEND_EXIT_NO_MYTHCONTEXT;
    }

    if (!MSqlQuery::testDBConnection())
    {
        VERBOSE(VB_IMPORTANT, "mythwelcome: Could not open the database. "
                        "Exiting.");
        return -1;
    }

    // Check command line arguments
    for (int argpos = 1; argpos < a.argc(); ++argpos)
    {

        if (!strcmp(a.argv()[argpos],"-v") ||
            !strcmp(a.argv()[argpos],"--verbose"))
        {
            if (a.argc()-1 > argpos)
            {
                if (parse_verbose_arg(a.argv()[argpos+1]) ==
                        GENERIC_EXIT_INVALID_CMDLINE)
                    return FRONTEND_EXIT_INVALID_CMDLINE;

                ++argpos;
            }
            else
            {
                cerr << "Missing argument to -v/--verbose option\n";
                return FRONTEND_EXIT_INVALID_CMDLINE;
            }
        }
        else if (!strcmp(a.argv()[argpos],"-s") ||
            !strcmp(a.argv()[argpos],"--setup"))
        {
            bShowSettings = true;
//---------------------------------------------
        if (a.argc()-1 > argpos)
            {
                QString tmpArg = a.argv()[argpos+1];
                if (tmpArg.startsWith("-"))
                {
                    cerr << "Invalid or missing argument to -s \n";
                    return FRONTEND_EXIT_INVALID_CMDLINE;
                }

                QStringList pairs = QStringList::split(",", tmpArg);
                for (unsigned int index = 0; index < pairs.size(); ++index)
                {
                    if ( pairs[index]  == "network" )
                        {
                        //  cout << pairs[index] << endl;
                            bShowNetwork = true;
                            modulelist.append("network,");
                        }
                        else if ( pairs[index]  == "misc" )
                        {
                        //  cout << pairs[index] << endl;
                            bShowMisc = true;
                            modulelist.append("misc,");
                        }
                        else if ( pairs[index]  == "sleep" )
                        {
                        // cout << pairs[index] << endl;
                            bShowshutdown = true;
                            modulelist.append("sleep,");
                        }
                        else if ( pairs[index]  == "hostype" )
                        {
                        //  cout << pairs[index] << endl;
                            bShowHostype = true;
                            modulelist.append("hostype,");
                        }
                        else if ( pairs[index]  == "advanced" )
                        {
                        // cout << pairs[index] << endl;
                            bShowadvanced = true;
                            modulelist.append("advanced,");
                        }
                        else if ( pairs[index]  == "sound" )
                        {
                        // cout << pairs[index] << endl;
                            bShowsound = true;
                            modulelist.append("audio,");
                        }
                        else if ( pairs[index]  == "advancedX" )
                        {
                        // cout << pairs[index] << endl;
                            bShowadvancedX = true;
                            modulelist.append("advancedX,");
                        }
                        else if ( pairs[index]  == "accesscontrol" )
                        {
                        // cout << pairs[index] << endl;
                            bShowAccesscontrol = true;
                            modulelist.append("accesscontrol,");
                        }
                        else if ( pairs[index]  == "plugins" )
                        {
                        // cout << pairs[index] << endl;
                            bShowplugins = true;
                            modulelist.append("plugins,");
                        }
                        else if ( pairs[index]  == "user" )
                        {
                        // cout << pairs[index] << endl;
                            bShowuser = true;
                            modulelist.append("user,");
                        }
                        else if ( pairs[index]  == "webuser" )
                        {
                        // cout << pairs[index] << endl;
                            bShowwebuser = true;
                            modulelist.append("webuser,");
                        }
                        else if ( pairs[index]  == "ddns" )
                        {
                        // cout << pairs[index] << endl;
                            bShowddns = true;
                            modulelist.append("ddns,");
                        }
                        else if ( pairs[index]  == "ir" )
                        {
                        // cout << pairs[index] << endl;
                            bShowinfrared = true;
                            modulelist.append("ir,");
                        }
                        else if ( pairs[index]  == "screensaver" )
                        {
                        // cout << pairs[index] << endl;
                            bShowscreensaver = true;
                            modulelist.append("screensaver,");
                        }

                }
            // return FRONTEND_EXIT_OK;
            }
            else
            {
            // if no args, then show the default steup.
            bShowNetwork = true;
            bShowHostype = true;
            bShowMisc = true;
            bShowuser = true;
            bShowshutdown = true;

            modulelist="network,hostype,misc,sleep";

            }

            ++argpos;


//---------------------------------------------
        }
        else if (!strcmp(a.argv()[argpos],"-u"))
            bShowuser = true;
        else if (!strcmp(a.argv()[argpos],"-t"))
        {
            bShowTemplate = true;
        if (a.argc()-1 > argpos)
            {
                QString tmpArg = a.argv()[argpos+1];
                if (tmpArg.startsWith("-"))
                {
                    cerr << "Invalid or missing argument to -t \n";
                    return FRONTEND_EXIT_INVALID_CMDLINE;
                }
                template_c_line = QStringList::split(",", tmpArg);
                if ( template_c_line.size() != 0 )
                    {
                    if  ( template_c_line.size()  >3     ||  template_c_line.size() <2 )
                        {
                            cerr << "Invalid or missing argument to -t \n";
                            return FRONTEND_EXIT_INVALID_CMDLINE;
                        }
                    }
                ++argpos;
        }

        }
        else if (!strcmp(a.argv()[argpos],"-b"))
        {
            bRunSetup = true;
        }
        else if (!strcmp(a.argv()[argpos],"-h"))
        {
            bShowHelp = true;
        }
        else if (!strcmp(a.argv()[argpos],"-r"))
        {
            bShowReadme = true;
        }
        else
        {
            cerr << "Invalid argument: " << a.argv()[argpos] << endl <<
                    "Valid options are: " << endl <<
                    "-v or --verbose debug-level    Use '-v help' for level info" << endl <<
                    "-b  run backend setup" << endl <<
                    "-h for help screens  " << endl <<
                    "-t show template screens  (op,tname,hname)" << endl <<
                    "-s or --setup (network,hostype,misc,sleep,advanced,advancedX,sound,accesscontrol,                  user,webuser,ddns,ir,screensaver)" << endl;
            return FRONTEND_EXIT_INVALID_CMDLINE;
        }
    }

    gContext->LoadQtConfig();

    LanguageSettings::load("mythfrontend");

    MythMainWindow *mainWindow = GetMythMainWindow();
    // if parms were passed to -t then doen't init the screen.
    if (   template_c_line.size()  == 0 )
    {
        gContext->SaveSetting("HOSTtemplatetype","Do Nothing" );
        mainWindow->Init();
        gContext->SetMainWindow(mainWindow);
    };
        initKeys();


    if (bShowSettings)
    {
        bool runconfig = false;
        system("cp -f /etc/systemconfig /tmp/systemconfig.bak");
        QString olddb = gContext->GetSetting("HostMysqlserver");
        QString oldhostype = gContext->GetSetting("HostSystemType");
        runsettings(false,bShowNetwork,bShowHostype,bShowMisc,bShowshutdown,bShowadvanced,bShowsound,bShowadvancedX,bShowAccesscontrol,bShowplugins,bShowuser,bShowwebuser,bShowddns,bShowinfrared,bShowscreensaver);
        QString newdb = gContext->GetSetting("HostMysqlserver");
        QString newhostype = gContext->GetSetting("HostSystemType");
        int status = system("diff /tmp/systemconfig.bak /etc/systemconfig");
        bool restart = false;

        // save my settings in case db switches
        //cout << "save for the heck of it " << endl;
        QString cmdtxt;
        cmdtxt=MV_ROOT  ;
        cmdtxt.append("bin/restore_default_settings.sh -c save -t syssettings  -d "  + olddb);
        system(cmdtxt);
        //system("/root/restore_default_settings.sh -c save -t syssettings  -d "  + olddb);

        if ( status != 0 )
        {
                runconfig = true;
        }

        if ( newdb != olddb )
            {
            runconfig = true;
            restart = true;
            //db changed save setting from olddb
            // cout << "newdb_olddb" << endl;
            QString cmdtxt;
                cmdtxt=MV_ROOT  ;
                cmdtxt.append("bin/restore_default_settings.sh -c save  -t  syssettings  -d " + olddb ) ;
                system(cmdtxt);
            //system("/root/restore_default_settings.sh -c save  -t  syssettings  -d " + olddb ) ;
            }

        if ( runconfig )
            {
                if ( newhostype != oldhostype )
                    modulelist.append("hostypec,");
                //trim off last ,
                modulelist.truncate(modulelist.length()-1);


                cout << modulelist <<endl;
                QString cmdtxt;
                cmdtxt=MV_ROOT  ;
                cmdtxt.append("bin/restore_default_settings.sh -c restore -t syssettings -d  ");
                QString dbcommand = cmdtxt;
                //QString dbcommand="/root/restore_default_settings.sh -c restore -t syssettings -d  ";
                dbcommand.append(newdb);
                //  cout << dbcommand << endl;
                run_systemconfig(modulelist,restart,dbcommand);
                //   cout << "running config" <<endl;
            }
        system("rm -f /tmp/systemconfig.bak");

        if ( restart )
           {
                //restore settings to new database
                //cout << " restoreing settings to new db" << endl;
                //system("/root/restore_default_settings.sh save   syssettings  " + olddb ) ;
            // system("/root/restore_default_settings.sh restore syssettings " + newdb) ;
                    DialogBox *dia = NULL;
                QString prompt;
                QString *problems = new QString("The network address of the database has changed.");
                problems->append("\n");
                problems->append("The frontend will need to restart to connect to the new database.");
                problems->append("\n");
                dia = new DialogBox(mainWindow, problems->append("\n" ));
                dia->AddButton(QObject::tr("OK"));
                int returncode = 0;
                returncode = dia->exec();
                dia->deleteLater();
                cout << "restarting" << endl;
                //system("/root/systemconfig.sh  restartfe" );
                QString cmdtxt;
                cmdtxt=MV_ROOT  ;
                cmdtxt.append("bin/systemconfig.sh  reloadfe" );
                system(cmdtxt);
            }

    }
    else if (bShowTemplate)
    {
    //  cout << templateparms << endl;
        if ( template_c_line.size() == 2)
        {
                templateop=template_c_line[0];
                templatename=template_c_line[1];
        }
        else if ( template_c_line.size() == 3)
        {
            templateop=template_c_line[0];
            templatename=template_c_line[1];
            templatehostname=template_c_line[2];
        };
        choosetemplate(templateop,templatename,templatehostname);
    }

    else if (bRunSetup)
    {
        DialogBox *dia = NULL;
        QString prompt;
        QString *problems = new QString("To configure the TV cards and program guide the setup program needs to be run.");
        problems->append("\n");
        problems->append("\n");

        problems->append("For those in North America, guide data is provided by Schedules Direct.");
        problems->append("\n");
        problems->append("Visit  http://www.schedulesdirect.org/  to signup for your account today");
        problems->append("\n");         problems->append("\n");          problems->append("\n");

        problems->append("If you choose to not run mythtv-setup now, the program can be run at any time by typing mythtv-setup or hitting ALT+s");
        problems->append("\n");

        problems->append("\n");
        prompt = QObject::tr("Do you wish to run mythtv-setup ?");

            dia = new DialogBox(mainWindow, problems->append("\n" + prompt));
            dia->AddButton(QObject::tr("Yes"));
            dia->AddButton(QObject::tr("Yes and try to autodetect cards"));
            dia->AddButton(QObject::tr("No"));
            int returncode = 0;
            //returncode = dia->exec();
            DialogCode dcode = dia->exec();
            dia->deleteLater();
            if (kDialogCodeButton0 == dcode )
                returncode = 0;
            if (kDialogCodeButton1 == dcode )
                returncode = 1;
            if (kDialogCodeButton2 == dcode )
                returncode = 2;

            if (returncode == 1)
            {
                AutoCard listcards;
                listcards.exec();
                }

            return returncode;


    }
else if (bShowHelp)
    {
        DialogBox *dia = NULL;
        QString prompt;
        QString *problems = new QString("			Help Screen");
        problems->append("\n");
        problems->append("-------------------------------------------------");
        problems->append("\n");
        problems->append("Alt+h This screen");
        problems->append("\n");
        #ifdef __MVAPP__
            problems->append("F2 open/close  terminal");
            problems->append("\n");
            problems->append("Shift + Return  opens new xterm");
            problems->append("\n");
            problems->append("Alt+F2 for 2nd desktop  Alt+F1 to go back");
            problems->append("\n");
            problems->append("Alt+c Capture myth screenshot");
            problems->append("\n");
        #else
            problems->append("Alt + X  opens new xterm ");
            problems->append("\n");
            problems->append("Alt + m  start mythfrontend");
            problems->append("\n");
            problems->append("m will display a popup for power/about");
            problems->append("\n");
        #endif
        problems->append("Ctrl + Alt + u  unhide  mouse cursor");
        problems->append("\n");
        problems->append("Alt+1 start   masterbackend");
        problems->append("\n");
        problems->append("Alt+2 stop    masterbackend");
        problems->append("\n");
        problems->append("Alt+3 restart masterbackend");
        problems->append("\n");
        problems->append("Alt+s  run mythtv-setup");
        problems->append("\n");


            dia = new DialogBox(mainWindow, problems->append("\n" ));
            dia->AddButton(QObject::tr("OK"));
        // dia->AddButton(QObject::tr("No"));
            int returncode = 0;
            returncode = dia->exec();
            dia->deleteLater();
            return returncode;


    }
else if (bShowReadme)
    {
        DialogBox *dia = NULL;
        QString prompt;
        QString line;
        QString *problems = new QString("");
        problems->append("\n");
        QFile file("/usr/MythVantage/README");
        if ( file.open(IO_ReadOnly | IO_Translate) )
        {
        QTextStream t( &file );        // use a text stream
            while ( !t.eof() )
            {
                line = t.readLine();
                problems->append(line);
                problems->append("\n");
            }
            file.close();
        }
        else
            problems->append("Couldn't open file");

        dia = new DialogBox(mainWindow, problems->append("\n" ));
        dia->AddButton(QObject::tr("OK"));
    // dia->AddButton(QObject::tr("No"));
        int returncode = 0;
        returncode = dia->exec();
        dia->deleteLater();
        return returncode;
    }
    else

    {
        WelcomeDialog *mythWelcome = new WelcomeDialog(gContext->GetMainWindow(),
                                                    "welcome_screen", "install-",
                                                "welcome_screen");

        mythWelcome->exec();


    delete mythWelcome;
    }

//  delete gContext;

    return 0;
}