#include <mythcontext.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include "settings.h"
#include "installsettings.h"
#include "installdialog.h"
#include "settemplate.h"
#include <qsqldatabase.h>
#include <qsqlquery.h>
#include <stdlib.h>
#include <cstdlib>

#include <mythtv/mythdbcon.h>

void create_temp_table (QString create_table_name,QString like_name)
{
   MSqlQuery query(MSqlQuery::InitCon());
   query.prepare("create table " +  create_table_name + " like  " +   like_name + ";" );
    query.exec();
    if ( like_name == "settings")
    {
        query.prepare("Alter table  " + create_table_name +  " add unique ( value ) ; " );
        query.exec();
    }
    query.prepare(" truncate " + create_table_name + ";" );
    query.exec();
};

void drop_temp_table (QString tname)
{
    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare("drop table " +  tname + ";" );
    query.exec();
}

void restart_frontend ()
{

    QString cmdtxt;
    cmdtxt=MV_ROOT  ;
    cmdtxt.append("bin/systemconfig.sh  reloadfe" );
    cout << "Calling systemconfig.sh reloadfe" << endl;
    system(cmdtxt);
    //system("/root/systemconfig.sh  reloadfe" );
}

void choosetemplate (QString templateop, QString templatename  , QString templatehostname = "")
{
        if ( templateop == ""  )
        {
        MythCtemplate setting;
        setting.load();
        setting.save();
      	setting.exec();
         };

    	QString thistemplate;
    	QString thisoperation;
        QString thishost;
        //QString runcommand = "/root/restore_default_settings.sh";
        QString runcommand = "echo ";
       // cout <<  templateop << endl;
       // cout << templatename << endl;
       // cout << templatehostname << endl;

        if (templateop == "")
            	   thisoperation = gContext -> GetSetting("HOSTtemplatetype");
        else
                   thisoperation = templateop;

        thistemplate = "none";


  	if ( thisoperation == "save" )
	{
        if (templatename == "" )
    	    thistemplate = gContext -> GetSetting("HostTemplateSave");
        else
            thistemplate = templatename;

        savesettings(thistemplate);
	}
	else if ( thisoperation == "restore" )
	{
       if (templatename == "" )
    	    thistemplate = gContext -> GetSetting("HostTemplateRestore");
        else
            thistemplate = templatename;

        if ( thistemplate == "default_1")
             c_from("default_1" , thistemplate);
        else if ( thistemplate == "default_2")
             c_from("default_2" ,thistemplate);
        else
             restoresettings(thistemplate);

	}
    else if ( thisoperation == "copy_from" )
	{
        if (templatename == "" )
        {
            thishost = gContext ->GetSetting("HostSelectcopy_from");
            thistemplate = gContext ->GetSetting("HostTemplateRestore");
        }
        else
        {
            thishost=templatehostname;
            thistemplate=templatename;
        };

        c_from(thishost,thistemplate);
	}


//	if ( thistemplate != "none" )
//	{
// 	    std::cout <<  runcommand << endl;
   	 //   system(runcommand);
	//}
};


void savesettings (QString templatenumber )
{
    cout << "SAVING....." <<   templatenumber  << endl;
    QString templatename = "settings_" + templatenumber ;
    // Remove old saved values
    MSqlQuery query(MSqlQuery::InitCon());
     query.prepare( "delete from "  + templatename +  " where hostname=:HOSTNAME   ;"  );
    query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    query.exec();
    //insert all new settings
    query.prepare( "replace into "  + templatename +  " (select * from settings where hostname=:HOSTNAME  ) ;"  ) ;
    query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    query.exec();

     // repeat for keybindings
     templatename = "keybindings_" + templatenumber ;
     query.prepare( "delete from "  + templatename +  " where hostname=:HOSTNAME   ;"  );
    query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    query.exec();

     query.prepare( "replace into "  + templatename +  " (select * from keybindings  where hostname=:HOSTNAME  ) ;"  );
    query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    query.exec();

}

void restoresettings (QString templatenumber )
{
 cout << "RESTORING....." << templatenumber << endl;
// DEFAULT settings are handled by the copy from routine
  MSqlQuery query(MSqlQuery::InitCon());
    QStringList tablelist ;
    QStringList::Iterator it;
    QString current_table;
    tablelist.append ("settings");
    tablelist.append ("keybindings");
    QString templatename;

    for ( it = tablelist.begin(); it != tablelist.end(); ++it )
    {
     current_table = *it ;
    //find template table to use
    QString templatename =  current_table + "_" + templatenumber ;
    QString temptable="temp_table_" + current_table + "_" +   gContext->GetHostName() ;
     // create temp table for merging settings,  The merge is needed to accoutn for any new settings.
    create_temp_table(temptable, current_table );

    // copy in current settings
    query.prepare( "replace into  " + temptable + "  (select * from  " + current_table + "  where hostname=:HOSTNAME ) ; "  );
    query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    query.exec();

    // need to remove all non HOST settigns

    // copy in stored settings
    query.prepare( "replace into  " + temptable + "  (select * from  " + templatename + "  where hostname=:HOSTNAME ) ; "  );
    query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    query.exec();

     // remove current settings.  Need to remove because the old table allows for duplicates and replace into doesn' seem to "replace"
     query.prepare( "delete from " + current_table + "  where hostname=:HOSTNAME ;"  );
     query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
     query.exec();


     // copy new settings from temp to current
     query.prepare( "replace into " + current_table  + "   (select * from  " + temptable + "  );"  );
     query.exec();

    // drop temptable
     drop_temp_table(temptable);

    }
restart_frontend();
};

void c_from(QString copyhost, QString templatenumber)
{
       cout << "Copying....." + copyhost + " " + "templatenumber"   << endl;
     MSqlQuery query(MSqlQuery::InitCon());
    //Create temp table, copy in settings from host_template, update hostname for new host,copy temp_table to settings.
     QStringList tablelist ;
    QStringList::Iterator it;
    QString current_table ;
    tablelist.append ("settings");
    tablelist.append ("keybindings");
    QString templatename;
    QString temptable;
    for ( it = tablelist.begin(); it != tablelist.end(); ++it )
    {
        current_table = *it ;
        cout << current_table << endl;
       //find template table to use
       if  ( templatenumber == "Current" )
             templatename =  current_table  ;
        else
             templatename =  current_table + "_" + templatenumber ;

       temptable="temp_table_" + current_table + "_" +   gContext->GetHostName() ;
        // create temp table for merging settings

        create_temp_table(temptable, current_table );
        cout << temptable + "  "         + current_table << endl;

  //  copy current settings from  this host  into temptable minus all Mythvantage settings
      if ( current_table == "settings")
        {
           query.prepare( "replace into  " + temptable + "    (select * from  " + current_table + "  where hostname=:HOSTNAME and value not like 'HOST%'  ) ; "  );
           query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
        }
        else
         query.prepare( "replace into  " + temptable + "    (select * from  " + current_table + " where hostname=:HOSTNAME ) ; "  );
         query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
         query.exec();

   // update hostname to match whatever the hostname of the template is
    query.prepare ("update " + temptable + "  set hostname=:HOSTNAME ; " );
    query.bindValue( ":HOSTNAME" ,  copyhost  );
    query.exec();

     // copy current settings from copy host  into temptable minus all Mythvantage settings
      if ( current_table == "settings")
          query.prepare( "replace into  " + temptable + "    (select * from  " + templatename  + "  where hostname=:HOSTNAME and value not like 'HOST%'  ) ; "  );

      else
            query.prepare( "replace into  " + temptable + "    (select * from  " + templatename  + "  where hostname=:HOSTNAME  ) ; "  );

      query.bindValue( ":HOSTNAME" ,  copyhost  );
      query.exec();

  //update hostname
    query.prepare ("update " + temptable + "  set hostname=:HOSTNAME ; " );
    query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    query.exec();

    // delete old settings from settings table
    if ( current_table == "settings")
    {
        query.prepare( "delete from " + current_table + "   where hostname=:HOSTNAME and value not like 'HOST%' ;"  );
        query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    }
    else
    {
        query.prepare( "delete from " + current_table + "   where hostname=:HOSTNAME ;"  );
        query.bindValue( ":HOSTNAME" ,   gContext->GetHostName()  );
    }
    query.exec();

    // copy settings from temptable to settings
     if ( current_table == "settings")
       query.prepare( "replace into " + current_table + "   (select * from  " + temptable + " where value not like 'HOST% ' ) ;"  );
    else
         query.prepare( "replace into " + current_table + "   (select * from  " + temptable + " );"  );


      query.exec();

  //  drop temptable
   // drop_temp_table(temptable);


restart_frontend();
};


};




 static HostComboBox *HOSTtemplatetype()
{
    HostComboBox *gc = new HostComboBox("HOSTtemplatetype");
    gc->setLabel(QObject::tr("Template options"));
    gc->addSelection("Do Nothing") ;
    gc->addSelection("restore");
    gc->addSelection("save") ;
    gc->addSelection("copy_from");

    gc->setHelpText(QObject::tr("Select the name to save, this will make a copy of your keybindings and videoplayback.  Choose none if you do not wish to change anything."));

    return gc;
}

 static HostComboBox *HostTemplateSave()
{
    HostComboBox *gc = new HostComboBox("HostTemplateSave");
    gc->setLabel(QObject::tr("Save Template"));
 //   gc->addSelection("none");
    gc->addSelection("user1") ;
    gc->addSelection("user2") ;
    gc->addSelection("user3") ;
    gc->setHelpText(QObject::tr("Select the name to save, this will make a copy of your keybindings and videoplayback.  Choose none if you do not wish to change anything."));

    return gc;
}
 static HostComboBox *HostTemplateCopy_restore()
{
    HostComboBox *gc = new HostComboBox("HostTemplateRestore");
    gc->setLabel(QObject::tr("Template"));
  //  gc->addSelection("none");
    gc->addSelection("Current");
    gc->addSelection("user1") ;
    gc->addSelection("user2") ;
    gc->addSelection("user3") ;
    gc->setHelpText(QObject::tr("Select the template you wish to restore.  This will change the way Myth repsonds to you remote buttons.  Choose none if you do not wish to change anything."));

    return gc;
}

 static HostComboBox *HostTemplateRestore()
{
    HostComboBox *gc = new HostComboBox("HostTemplateRestore");
    gc->setLabel(QObject::tr("Template"));
  //  gc->addSelection("none");
    gc->addSelection("default_1");
    gc->addSelection("default_2");
    gc->addSelection("user1") ;
    gc->addSelection("user2") ;
    gc->addSelection("user3") ;
    gc->setHelpText(QObject::tr("Select the template you wish to restore.  This will change the way Myth repsonds to you remote buttons.  Choose none if you do not wish to change anything."));

    return gc;
}

 static HostComboBox *HostSelectcopy_from()
{
    HostComboBox *gc = new HostComboBox("HostSelectcopy_from");
    gc->setLabel(QObject::tr("Host"));
  //  gc->addSelection("none");

   QString tempItem;

    MSqlQuery query(MSqlQuery::InitCon());

    query.prepare( "SELECT DISTINCT hostname from settings where hostname is not null;");

      if (query.exec() && query.isActive() && query.size() > 0)
    {
        while (query.next())
        {
            tempItem = query.value(0).toString();
            gc->addSelection(tempItem);

        }
    }
    gc->setHelpText(QObject::tr("Select the Host you wish to copy settings from."));

    return gc;
}

class TemplateSettings:
                       public TriggeredConfigurationGroup {
public:
    TemplateSettings():
         //ConfigurationGroup(false, true, false, false),
         //VerticalConfigurationGroup(false, true, false, false),
         TriggeredConfigurationGroup(true) {
         setLabel(QObject::tr("Manage templates"));
//         setUseLabel(false);

         Setting* Mtemplate = HOSTtemplatetype();
         addChild(Mtemplate);
         setTrigger(Mtemplate);


         ConfigurationGroup* trestore = new VerticalConfigurationGroup(false);
         trestore->addChild(HostTemplateRestore());

  	     ConfigurationGroup* tsave = new VerticalConfigurationGroup(false);
         tsave->addChild(HostTemplateSave());

        ConfigurationGroup* tcopy = new VerticalConfigurationGroup(false);
         tcopy->addChild(HostSelectcopy_from());
         tcopy->addChild(HostTemplateCopy_restore());


        addTarget("Do Nothing", new VerticalConfigurationGroup(true));
	    addTarget("restore", trestore);
	    addTarget("save", tsave);
        addTarget("copy_from", tcopy);

     };
};

MythCtemplate::MythCtemplate()
{

        TemplateSettings *templatesettings = new TemplateSettings();
        addChild(templatesettings);

}