/***************************************************************************
                          knutmainwindow.cpp  -  description
                             -------------------
    begin                : Po cen 16 2003
    copyright            : (C) 2003 by Daniel Prynych
    email                : Daniel.Prynych@alo.cz
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/


#include "knutmainwindow.h"
#include "knutvardata.h"

#include <tdemessagebox.h>
#include <kstdaction.h>
#include <tdeconfig.h>
#include <ksimpleconfig.h>
#include <kstatusbar.h>
#include <kkeydialog.h>
#include <kprogress.h>


#include <tqfont.h>
#include <tqpalette.h>
#include <tqbrush.h>
#include <tqcolor.h>
#include <tqstring.h>
#include <tqscrollview.h>
#include <tqlayout.h>
#include <tqiconset.h>
#include <tqstring.h>
#include <tqstringlist.h>
#include <tqlabel.h>
#include <tqsplitter.h>
//#include <tqprogressbar.h>




#include <math.h>
#include <stdlib.h>
#include <unistd.h>

#include <iostream>



extern const char *nameUpsVars1[];
extern const char *nameUpsVars2[];

const char *descrOfConnection = I18N_NOOP("test of conection from 5");



KNutMainWindow::KNutMainWindow(TQStringList *tListKNutEvent, KNutVarData::upsInfoDef* tActiveUpsInfo, KNutVarData::SettingDataDef* tSettingData, KNutUpsData* tUpsRecords, KNutVarData* tAnalogRecords, TQWidget* parent, const char *name) : TDEMainWindow(parent, name),
                   m_listKNutEvent(tListKNutEvent), m_activeUpsInfo(tActiveUpsInfo),m_settingData (tSettingData),
                   m_upsRecords(tUpsRecords), m_analogRecords (tAnalogRecords) {



  m_settingData->activatedMainWindow=true; //information about state of mainWindow

  initVars();
  initStatusBar();
  initAction();
//  createGUI ("/home/dan/Projekty/knutclient/src/knutclientui.rc"); // pred distribuci nezapomenout odstranit retezec
  // createGUI vytvori zakladni strukturu podle souboru knutclientui.rc
  createGUI ();
  initToolBar ();


  m_descriptionAction->setChecked(m_settingData->useDescription);

  //sets input frequency and input voltage   
  //nastavime vstupni frekvenci a vstupni napeti
  m_analogRecords->setFrequency(m_settingData->inputFrequency);
  m_analogRecords->setVoltage(m_settingData->inputVoltage);

  //sets palette for analog panels
  // nastavime paletu pro analogove panely
  if (m_settingData->customBAnalogColor) {
    m_aPanelPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->aPanelBackgroundColor);
    m_aPanelPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->aPanelBackgroundColor);
    }

 if (m_settingData->customBColor) {
    m_areaPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->mainBackgroundColor);
    m_areaPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->mainBackgroundColor);
    }


  // makes main area // Vytvorime hlavni plochu
  m_area = new TQLabel (this);
  setCentralWidget (m_area);

  TQHBoxLayout* mainLayout = new TQHBoxLayout(m_area);
  m_mainSplit = new TQSplitter(TQt::Horizontal,m_area);
  m_mainSplit->setOpaqueResize(true);

  mainLayout->addWidget(m_mainSplit);
  if (m_settingData->customBPanelColor) {
    m_mPanelPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->mPanelBackgroundColor);
    m_mPanelPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->mPanelBackgroundColor);
    }

  TQScrollView* panelSV = new TQScrollView(m_mainSplit,"panelSV");
  if (m_settingData->customFont)
    m_frontPanel = new KNutFrontPanel (&m_mPanelPalette,m_mainSplit,m_settingData->panelFlags,&(m_settingData->mPanelFont),"FrontPanel");
  else
    m_frontPanel = new KNutFrontPanel (&m_mPanelPalette,m_mainSplit,m_settingData->panelFlags,&(m_settingData->systemFont),"FrontPanel");
  panelSV->addChild(m_frontPanel);
  panelSV->setResizePolicy ( TQScrollView::AutoOneFit ) ;
  m_mainSplit->setResizeMode (panelSV,TQSplitter::FollowSizeHint);

  m_panelMeter = new KNutPanelMeter(m_aPanelPalette,m_activeUpsInfo,m_settingData,m_analogRecords,m_mainSplit);
  m_mainSplit->setResizeMode (m_panelMeter,TQSplitter::Stretch );

  m_area->setPalette(m_areaPalette);
  m_panelMeter->setPalette(m_areaPalette);

  // sets Combo a actives connections to meter panels
  // Nastavime COMBO  a pripadne aktivujeme spojeni na merici panely
  int activeUpsNameIndex = activeMainCombo ();
  if (activeUpsNameIndex != -1) toolBar(0)->getCombo(1)->setCurrentItem( activeUpsNameIndex );

  showUpsData();
  setGeometry (m_settingData->x,m_settingData->y,m_settingData->width,m_settingData->height);
  show();


  //message has to include into status bar after showing window,
  // only for KDE relase < 3.0.0

  // jinak se nastavi minimalni velikost ne mensi nez delka aktivni zpravy.

  initStatusBarMessage();
  }



void KNutMainWindow::addComboStatusItem (const TQString text, const TQString name) {
  if (m_infoCombo->count() >= (int)knc::maxCountKNutEvent) m_infoCombo->removeItem(0);
  if (m_listKNutEvent->count() > knc::maxCountKNutEvent) m_listKNutEvent->remove(m_listKNutEvent->begin());

  TQString dateTime(TQDate::currentDate().toString());
  dateTime +=" " + TQTime::currentTime().toString();
  if (name.isEmpty()) {
    m_infoCombo->insertItem(dateTime+" "+text);
    m_listKNutEvent->append(dateTime+" "+text);
     }
  else {
    m_infoCombo->insertItem(dateTime+" "+name+" : "+text);
    m_listKNutEvent->append(dateTime+" "+name+" : "+text);
    }
  m_infoCombo->setCurrentItem(m_infoCombo->count()-1);
  if (m_listKNutEvent->count() > knc::maxCountKNutEvent) m_listKNutEvent->remove(m_listKNutEvent->begin());
  }


KNutMainWindow::~KNutMainWindow(void) {

  m_settingData->height = height();
  m_settingData->width = width();
  m_settingData->y = y();
  m_settingData->x = x();

  delete m_frontPanel;
  delete m_panelMeter;
  }


void KNutMainWindow::setConfig (unsigned int changeSetting) {


//tqDebug ("KNutMainWindow::setConfig");
  KNutVarData::VarStrucDef analogMemberData;
  bool repaintVoltagePanels = false;
  bool repaintFrequencyPanels = false;
  bool repaintAllPanels = false;
  bool repaintOAPanels = false;

  // Main Setting

  // Nastavime zmenu barvy pozadi
  // sets background color
  if (changeSetting & KNutPrefDlg::ChangeCustomBColor) {
    if (!m_settingData->customBColor) { // nastavime barvu pozadi podle systemu 
      m_area->setPalette (m_mainPalette); // we set background color based on system
      m_panelMeter->setPalette (m_mainPalette);
      repaint();
      }
    else {
      m_areaPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->mainBackgroundColor);
      m_areaPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->mainBackgroundColor);
      m_area->setPalette (m_areaPalette);
      m_panelMeter->setPalette (m_areaPalette);
      repaint();
      }
    }
  else {
    if (changeSetting & KNutPrefDlg::ChangeMBColor ) {
      m_areaPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->mainBackgroundColor);
      m_areaPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->mainBackgroundColor);
      m_area->setPalette (m_areaPalette);
      m_panelMeter->setPalette (m_areaPalette);
      repaint();
      }
    }

  // Sets background for panels
  // sets frequence
  // sets voltage
  // XFer is switch-on and one exist for this UPS


  if ((changeSetting & KNutPrefDlg::ChangeXFer) || // je provedena nejaka zmena na napeti nebo frekvence
      (changeSetting & KNutPrefDlg::ChangeVoltage) || (changeSetting & KNutPrefDlg::ChangeFrequency)) {

    if ((changeSetting & KNutPrefDlg::ChangeXFer) && (m_settingData->lowHighXfer) && (m_existLowHighXfer)) {
    // xfer was activated
      if (changeSetting & KNutPrefDlg::ChangeXFer) {
        if (abs((int)(230 - (m_lowXfer + (m_highXfer  - m_lowXfer) /2))) > abs((int)(120 - (m_lowXfer + (m_highXfer  - m_lowXfer) /2)))) {
          m_analogRecords->setVoltage(120);
          m_analogRecords->setFrequency(60);
          }
        else {
          m_analogRecords->setVoltage(230);
          m_analogRecords->setFrequency(50);
          }
        m_analogRecords->setXfer(m_lowXfer,m_highXfer);
        repaintVoltagePanels = true;
        repaintFrequencyPanels = true;
        }
      }
    else {
    // XFER neni aktivovano nebo je nepodporuje UPS
    // XFER isn;t activated or XFER isn't supported by UPS
    if ((changeSetting & KNutPrefDlg::ChangeVoltage) || ((changeSetting & KNutPrefDlg::ChangeXFer))) {
    // byla aktivovana zmena napeti nebo zmena xfer a zaroven ho ups podporuje
      m_analogRecords->setVoltage(m_settingData->inputVoltage);
      repaintVoltagePanels=true;
      }
    if ((changeSetting & KNutPrefDlg::ChangeFrequency) || ((changeSetting & KNutPrefDlg::ChangeXFer))) {
    // byla aktivovana zmena napeti nebo zmena xfer a zaroven ho ups podporuje
      m_analogRecords->setFrequency(m_settingData->inputFrequency);
      repaintFrequencyPanels=true;
      }
    }
  }

  // Analog setting
  // now DigitalProcesing of pointer
  if  (changeSetting & KNutPrefDlg::ChangeTypeOfDigProcessing) { //type of digital processing was changed
     m_panelMeter->changeAnalogPanelsDigProcessing(); //paint pointers with new digotal processing
     }

  if ((changeSetting & KNutPrefDlg::ChangeCustomAPanelBColor) || // barva panelu je zmenena, panel color is changed
      (changeSetting & KNutPrefDlg::ChangeAPBColor)) {
    if (m_settingData->customBAnalogColor) {
      m_aPanelPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->aPanelBackgroundColor);
      m_aPanelPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->aPanelBackgroundColor);
      repaintAllPanels=true;
      m_panelMeter->setAnalogBG(m_aPanelPalette);
      }
    else {
      m_aPanelPalette = m_mainPalette;
      repaintAllPanels=true;
      m_panelMeter->setAnalogBG(m_aPanelPalette);
      }
    }

  if ((changeSetting & KNutPrefDlg::ChangeCustomAPanelOColor) || // je provedena zmena barvy panelu
      (changeSetting & KNutPrefDlg::ChangeAPOColor)) {
     if (m_settingData->customOAnalogColor) {
       repaintAllPanels=true;
       repaintOAPanels=true;
       }
     else {
       repaintAllPanels=true;
       repaintOAPanels=true;
       }
    }
  // regeneration of panel uses for setting Main and setting Analog 
  // pregenerovani panelu slozi pro setting Main a setting Analog
  m_panelMeter->repaintAnalogPanels (repaintFrequencyPanels, repaintVoltagePanels, repaintAllPanels);

  if (m_activeUpsInfo->record.name != "") {
    m_panelMeter->setSize();
    m_mainSplit->refresh();
    }

  // UPS Setting
  if (changeSetting & KNutPrefDlg::ChangeUpsSetting ) activeMainCombo();
  else {
    if (changeSetting & KNutPrefDlg::ChangeUpsCount) activeMainCombo();
    }

  // Main Panel Setting
  // change of background color
  // zmena barvy pozadi;
  if (changeSetting & KNutPrefDlg::ChangeCustomMPanelBColor) {
    if (!m_settingData->customBPanelColor) { // nastavime barvu pozadi podle systemu
      m_frontPanel->setPalette (m_mainPalette);
      }
    else {
      m_mPanelPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->mPanelBackgroundColor);
      m_mPanelPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->mPanelBackgroundColor);
      m_frontPanel->setPalette (m_mPanelPalette);
      }
    }
  else {
    if (changeSetting & KNutPrefDlg::ChangeMPBColor ) {
      m_mPanelPalette.setColor(TQPalette::Active,TQColorGroup::Background,m_settingData->mPanelBackgroundColor);
      m_mPanelPalette.setColor(TQPalette::Inactive,TQColorGroup::Background,m_settingData->mPanelBackgroundColor);
      m_frontPanel->setPalette (m_mPanelPalette);
      }
    }

  if (changeSetting & KNutPrefDlg::ChangeMainPanelSetting ) {
    if (m_settingData->panelFlags != m_frontPanel->getPanelFlags()) {
      m_frontPanel->setPanelFlags(m_settingData->panelFlags);
      //aktivujema a presuneme prvky panelu
      // activates and moves items of panel
      m_frontPanel->paintPanel();
      }
    }

  // Font panel setting
  if (changeSetting & KNutPrefDlg::ChangeAnalogFont ) {
    TQFont newAnalogFont;
    if (m_settingData->customFont) {
      newAnalogFont=m_settingData->aPanelFont;
      }
    else {
      newAnalogFont=m_settingData->systemFont;
      }

    m_panelMeter->slotSetPanelsFont(newAnalogFont);
    }
  if (changeSetting & KNutPrefDlg::ChangePanelFont ) {
    TQFont newPanelFont;
    if (m_settingData->customFont) {
      m_frontPanel->slotSetPanelFont(m_settingData->mPanelFont);
      }
    else {
      m_frontPanel->slotSetPanelFont(m_settingData->systemFont);
      }
    }
  }




void KNutMainWindow::showUpsData (void) {

//tqDebug ("KNutMainWindow::showUpsData start");


  if ((m_activeUpsInfo->upsNet != 0L) && (!m_activeUpsInfo->netError) &&
     (m_activeUpsInfo->upsDriverState == knc::connected)) {
    int runtimeVal;
    TQString nutStringVar;
    bool okFloat;
//    activeUpsInfo->oldStatus=KNutNet::initStatus;

    // Nastaveni nemenych dat jsou precteny pouze jednou, predpoklada se jejich nemenost
    // setting of unchange data, ones are reading only one. 
    nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->lowxferVar);
    switch (m_activeUpsInfo->nutVariables) {
      case 1:
        m_manufacturer = m_activeUpsInfo->upsNet->readStringVar("MFR");
        m_upsModel = m_activeUpsInfo->upsNet->readStringVar("MODEL");
        m_serial = m_activeUpsInfo->upsNet->readStringVar("SERIAL");
        m_firmrev = m_activeUpsInfo->upsNet->readStringVar("FIRMREV");
      break;
      case 2:
        m_manufacturer = m_activeUpsInfo->upsNet->readStringVar("ups.mfr");
        m_upsModel = m_activeUpsInfo->upsNet->readStringVar("ups.model");
        m_serial = m_activeUpsInfo->upsNet->readStringVar("ups.serial");
        m_firmrev = m_activeUpsInfo->upsNet->readStringVar("ups.firmware");
      break;
      }  
    TQString allUpsName = m_manufacturer + " " + m_upsModel;
    m_frontPanel->setAllNameUps (allUpsName);
    m_frontPanel->setMFRUps (m_manufacturer);
    m_frontPanel->setNameUps (m_upsModel);
    m_frontPanel->setSerialUps (m_serial);
    m_frontPanel->setFirmRevUps (m_firmrev);
    // try if LOWXFER and HIGHXFER or our values are existed
    //Zjistime zda existuji LOWXFER a HIGHXFER pripadne jeji hodnoty

    if (nutStringVar.isNull()) {
      m_lowXfer =-1;
      m_highXfer=-1;
      m_existLowHighXfer = false;
      }
    else {
      m_lowXfer = nutStringVar.toFloat();
      nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->highxferVar);
      if (nutStringVar.isEmpty()) {
        m_highXfer = -1;
        m_existLowHighXfer = false;
        }
      else {
        m_highXfer = nutStringVar.toFloat();
        m_existLowHighXfer = true;
        }
      }
    int upsStatus=0;
    if ((upsStatus = m_activeUpsInfo->upsNet->readStatus ()) != -1)
      m_frontPanel->setPanel(upsStatus);

    if ( !m_activeUpsInfo->upsNet->existName(m_activeUpsInfo->runtimeVar)) {
      nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->runtimeVar);
      if (nutStringVar.isEmpty()) runtimeVal=knc::numberVarError;
      else {
        runtimeVal=(int)nutStringVar.toFloat(&okFloat);
        if (!okFloat) runtimeVal = knc::numberVarError;
        }
      }
    else runtimeVal=knc::numberVarError;
    m_frontPanel->setRuntime(runtimeVal);

    m_panelMeter->deActivateAnalogs();

    // pokud je pouzito XFER nastavime hodnoty
    // when XFER is used we set values
      if (m_settingData->lowHighXfer) {
        // xfer je nastaveno
        // xfer is seted
        if (m_existLowHighXfer) {
          if (abs((int)(230 - (m_lowXfer + (m_highXfer  - m_lowXfer) /2))) > abs((int)(120 - (m_lowXfer + (m_highXfer  - m_lowXfer) /2)))) {
            m_analogRecords->setVoltage(120);
            m_analogRecords->setFrequency(60);
            }
          else {
            m_analogRecords->setVoltage(230);
            m_analogRecords->setFrequency(50);
            }
          m_analogRecords->setXfer(m_lowXfer,m_highXfer);
          }
        }

//tqDebug ("KNutMainWindow::showUpsData 1");
    m_panelMeter->activateAnalogs(); // makes panel and makes background of panel
    repaintAnalogs(false);
//tqDebug ("KNutMainWindow::showUpsData 2");
    m_panelMeter->setSize(true);
//tqDebug ("KNutMainWindow::showUpsData 3");
    m_mainSplit->refresh();
    // doesn't repaint analog pointers, because pointers will be repainted twice
//tqDebug ("KNutMainWindow::showUpsData 4");
//    repaintAnalogs(false); // don't make this 
//tqDebug ("KNutMainWindow::showUpsData 5");
    }
  else {
    cleanPanels();
    }
  }


void KNutMainWindow::zeroingPanels (void) {

  m_panelMeter->zeroingPanels();
  m_frontPanel->setRuntime(knc::numberVarError);  
  m_frontPanel->setPanel(0);
  }


void KNutMainWindow::hideUpsData (void) {
  m_frontPanel->cleanPanel();
  }

void KNutMainWindow::setCombo (TQString name) {
  if (toolBar(0)->getCombo(1)->currentText() != name) toolBar(0)->getCombo(1)->setCurrentText(name);
  }

void KNutMainWindow::repaintPanel (void) {
  TQString nutStringVar;

  if (m_activeUpsInfo->upsNet == 0) return;
  if (!m_activeUpsInfo->upsNet->existName(m_activeUpsInfo->runtimeVar)) {
    nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->runtimeVar);
    if (nutStringVar.isEmpty()) m_frontPanel->setRuntime(0);
    else m_frontPanel->setRuntime( nutStringVar.toInt());
    }
  else m_frontPanel->setRuntime(knc::numberVarError);
  // precteme status a nastavime zarovky panelu
  int status = m_activeUpsInfo->upsNet->readStatus();
  m_frontPanel->setPanel(status);
  }


/// je volan vzdy po timeoutu
/// this function is called after timeout always
void KNutMainWindow::repaintAnalogs ( bool run ) {
//tqDebug ("KNutMainWindow::repaintAnalogs");


  TQString nutStringVar;
  float numVar;
  bool  newRange = false;

  if ((m_settingData->lowHighXfer) && (m_existLowHighXfer)) {
    TQString nutStringVar;

    nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->lowxferVar);
    if (! nutStringVar.isEmpty()) {
      float helpLowXfer = nutStringVar.toFloat();
      nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->highxferVar);
      if (! nutStringVar.isEmpty()) {
        float helpHighXfer = nutStringVar.toFloat();
        if ((helpLowXfer != m_lowXfer) || (helpHighXfer != m_highXfer)) {
          m_lowXfer=helpLowXfer;
          m_highXfer=helpHighXfer;
          m_analogRecords->setXfer(m_lowXfer,m_highXfer);
          newRange = true;
          }
        }
      }
    }

//tqDebug ("KNutMainWindow::repaintAnalogs 1");

  for (int i=0; i< knc::NumberOfVars; i++) {
    if (m_activeUpsInfo->record.upsVarCode[i] != 0) { // jistota pokud by nam to nekde propadlo
      switch (m_activeUpsInfo->nutVariables) {
        case 1:
          nutStringVar = m_activeUpsInfo->upsNet->readStringVar ((char *)nameUpsVars1[m_activeUpsInfo->record.upsVarCode[i]]);
        break;
        case 2:
          nutStringVar = m_activeUpsInfo->upsNet->readStringVar ((char *)nameUpsVars2[m_activeUpsInfo->record.upsVarCode[i]]);
        break;
        }
//tqDebug ("KNutMainWindow::repaintAnalogs 2 ");

      if (nutStringVar.isEmpty())  numVar=0;
      else numVar = nutStringVar.toFloat();

      m_panelMeter->repaintScaleAnalogPanel (i, numVar);
      if (newRange) m_panelMeter->repaintAnalogPanels (true, true, false); //freq volt
      m_panelMeter->repaintAnalogPointer(i,numVar,run);
      }
    } // end for
//tqDebug ("KNutMainWindow::repaintAnalogs 3 ");
  }



void KNutMainWindow::cleanPanels (void) {

  m_frontPanel->cleanPanel();
  m_panelMeter->deActivateAnalogs();
  m_panelMeter->setSize(false);
  m_mainSplit->refresh();
  }

void KNutMainWindow::startConnectPB ( const int count ) {
  m_connectProggresBar->setTotalSteps(count);
  m_connectProggresBar->setProgress(1);
  m_connectProggresBar->show();
  }


void KNutMainWindow::setProgressConnectPB ( const int progress ) {
  m_connectProggresBar->setProgress(progress);
  }


void KNutMainWindow::hideConnectPB ( void ) {
  m_connectProggresBar->setProgress(0);
  m_connectProggresBar->hide();
  }


/*********************************************************************************************/
/*                                                                                           */
/*                         PRIVATE SLOTS                                                     */
/*                                                                                           */
/*********************************************************************************************/


//this slot is for older KDE only
void KNutMainWindow::slotShowToolBar(void) {

  if(toolBar("mainToolBar")->isVisible()) toolBar("mainToolBar")->hide();
  else toolBar("mainToolBar")->show();
  }


void KNutMainWindow::slotShowStatusBar(void) {

  if(statusBar()->isVisible()) {
    statusBar()->hide();
    }
  else {
    statusBar()->show();
    }
  }

void KNutMainWindow::slotDescription(void) {

  if (m_descriptionAction->isChecked()) {
    if (!m_activeUpsInfo->upsNet->isDescription()) m_activeUpsInfo->upsNet->getDescription();
    m_settingData->useDescription=true;
    }
  else m_settingData->useDescription=false;
  emit saveConf();
  }


void KNutMainWindow::slotPrintUPSVars(void) {

  emit showUPSVars();
}


void KNutMainWindow::slotInstComms(void) {

  emit makeInstComms();
  }

void KNutMainWindow::slotRWVars(void) {

  emit makeRWVars();
  }

void KNutMainWindow::slotRefreshConnection(void) {

  emit makeRefreshConnection();
  }


void KNutMainWindow::slotChangeRWVars ( TQString ) {
  }



void KNutMainWindow::closeEvent( TQCloseEvent *e ){

  m_settingData->activatedMainWindow=false; //information about state of mainWindow
  e->accept();
  }



void KNutMainWindow::slotConfigureKeys() {

  KKeyDialog::configure( actionCollection(), this );
  }


void KNutMainWindow::slotCloseKnutClient (void) {
  if (m_settingData->areYouSure) {
    if (KMessageBox::warningYesNo (0,i18n("Are you sure ?")) == 3) 
      emit endApplication();
    }
  else emit endApplication();
  }




  void KNutMainWindow::slotChangeUPS (const TQString &name) {
  emit UPSChanged (name);
  }


void KNutMainWindow::slotPreferencesUps() {
    emit preferenceUps();
  }


/*********************************************************************************************/
/*                                                                                           */
/*                         PRIVATE FUNCTIONS                                                 */
/*                                                                                           */
/*********************************************************************************************/



void KNutMainWindow::initStatusBar ( void ) {
  // sets main message if statusbar
  // nastavime hlavni hlaseni v statusbaru

 // TQString progressString("%v ");// += descrOfConnection;
//  progressString.append(descrOfConnection);

  m_progressFormatString.append("%v ");
  m_progressFormatString.append(descrOfConnection);
  m_infoCombo = new KComboBox (statusBar(),"infoCombo");
  m_infoCombo->setMaxCount(knc::maxCountKNutEvent+1); // nastavime maximalni pocet polozek v Combu
                                                 // pro rezervu pridame jeste jednu
//sets maximal if items in Combo 
  statusBar()->addWidget(m_infoCombo,10,false);

  m_connectProggresBar = new KProgress(statusBar(),"connectProgressBar");
  statusBar()->addWidget(m_connectProggresBar,5,false);
  m_connectProggresBar->setProgress(0);
//  m_connectProggresBar->setFormat("%v test of conection from 5");
  m_connectProggresBar->setFormat(m_progressFormatString);
  m_connectProggresBar->hide();
  }


void KNutMainWindow::initStatusBarMessage ( void ) {
  // loads data into comboBox
  TQStringList::iterator it;

  for ( it = m_listKNutEvent->begin(); it != m_listKNutEvent->end(); ++it ) {
    m_infoCombo->insertItem((*it));
    }
  statusBar()-> setItemAlignment(0,TQt::AlignHCenter|TQt::AlignVCenter);
  m_infoCombo->setCurrentItem(m_infoCombo->count()-1);
  }


void KNutMainWindow::initToolBar ( void ) {

  TQLabel *upsNazev = new TQLabel ("UPS : ",toolBar("mainToolBar"));
  // upsNazev is connected on toolBaar, dosn't need to call desctructor
  toolBar ("mainToolBar")->insertWidget (0,upsNazev->sizeHint().width(),upsNazev);
  toolBar ("mainToolBar")->insertCombo("",1,false, TQ_SIGNAL (activated (const TQString &)),this, TQ_SLOT (slotChangeUPS (const TQString &)));
  // bude se pouze vybirat-------------------^^^
  KComboBox *combo = toolBar("mainToolBar")->getCombo(1);
  combo->clear();
  toolBar("mainToolBar")->setBarPos (TDEToolBar::Top);
  //sets toolbarr no movable /  nastavime toolBar nepresouvatelny
  setToolBarsMovable(false);
  }


void KNutMainWindow::initAction ( void ) {

  // TDEAction and KStdAction must be to make before command createGUI, function initToolBar is runed after create GUI
  m_quit = KStdAction::quit (this, TQ_SLOT (slotCloseKnutClient()), actionCollection());
  m_quit->setStatusText(i18n("Quits the application"));

  m_preferencesUps = KStdAction::preferences (this, TQ_SLOT (slotPreferencesUps()), actionCollection(),"options_configure");
  new TDEAction(i18n("&Showing UPS variables and commands"),0,this, TQ_SLOT(slotPrintUPSVars()),actionCollection(),"printupsvars");
  new TDEAction(i18n("&Running instant commands"),0,this, TQ_SLOT(slotInstComms()),actionCollection(),"instcomms");
  new TDEAction(i18n("Setting R&W variables"),0,this, TQ_SLOT(slotRWVars()),actionCollection(),"rwvars");

  setStandardToolBarMenuEnabled(true);

  KStdAction::showStatusbar (this, TQ_SLOT (slotShowStatusBar()), actionCollection());

  m_descriptionAction = new TDEToggleAction(i18n("&Using descriptions"),0,this, TQ_SLOT(slotDescription()),actionCollection(),"use_description");

  KStdAction::keyBindings( this, TQ_SLOT(slotConfigureKeys()),actionCollection());
  new TDEAction (i18n("Reconnect"),"reload",Key_F5,this, TQ_SLOT(slotRefreshConnection()),actionCollection(),"reconnect");
  }

void KNutMainWindow::initVars ( void ) {

  //m_activeUpsIndex = -1;

  //nastavime fonty
  // sets fonts
  m_mainPalette= kapp->palette();
  m_areaPalette=m_mainPalette;
  m_mPanelPalette=m_mainPalette;
  m_aPanelPalette=m_mainPalette;
  }


int KNutMainWindow::activeMainCombo (void) {
  int activeUpsNameIndex = -1; // zadne upsName neni aktivni , any upsName is not active
  KComboBox *combo = toolBar(0)->getCombo(1);

  //naplnime comboBox
  //loads comboBox
  combo->clear();
  for (int i=0; i < m_upsRecords->getCount (); i++) {
    combo->insertItem (m_upsRecords->getName(i));
    // ulozime si poradove cislo jmena aktivniho ups
    // save serial number of active usp name
    if ((m_upsRecords->getName(i)) == m_activeUpsInfo->record.name) activeUpsNameIndex = i;
    }
  return activeUpsNameIndex;
  }

#include "knutmainwindow.moc"
