/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/***************************************************************************
 *            mainwindow.cc
 *
 *  Sat Aug 21 19:49:34 2004
 *  Copyright  2004  deva
 *  deva@aasimon.org
 ****************************************************************************/

/*
 *    This file is part of MIaV.
 *
 *    MIaV 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.
 *
 *    MIaV 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 MIaV; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */

/*
 * $Id$
 */

/*
 * $Log$
 * Revision 1.25  2005/05/03 09:22:12  deva
 * Implemented the gui part of the info object.
 *
 * Revision 1.24  2005/05/03 08:31:59  deva
 * Removed the error object, and replaced it with a more generic info object.
 *
 * Revision 1.23  2005/05/02 20:34:38  deva
 *
 * Some hacked borky ugly scumm code to check for errors! :(
 *
 * Revision 1.22  2005/05/02 19:56:17  deva
 *
 * cpr_clicked is now blocked, if a recording session on. A messagebox explains
 * how to stop before trying to change the cpr number again.
 *
 * Revision 1.21  2005/05/02 18:47:21  deva
 *
 * Cpr now sent to decoder. And saved prioer to editing, in order to be able
 * to disable editing session and revert to old cpr.
 *
 * Revision 1.19  2005/05/01 12:13:50  deva
 * Removed bitmap readin.
 *
 * Revision 1.18  2005/05/01 12:04:15  deva
 * Using qbitmap for raw pixel readin.
 *
 * Revision 1.17  2005/05/01 11:25:56  deva
 * Added code to read screenshot from frame queue, decode it to rgb and put it into a qimage.
 *
 * Revision 1.16  2005/05/01 09:56:26  deva
 * Added Id and Log tags to all files
 */

#include <config.h>
#ifdef USE_GUI

#include "mainwindow.h"

#include <qpainter.h>
#include <qpicture.h>

#include <qpushbutton.h>
#include <qfont.h>
#include <qpixmap.h>
#include <qbitmap.h>
#include <qimage.h>
#include <qlayout.h>
#include <qgroupbox.h>

#include <qstatusbar.h>

#include <math.h>

//#include "mgui_alert.h"
//#include "mgui_datasocket.h"

#include "miav_config.h"

#include <config.h>
//"miav-grab.h"


//#define WITH_DV
MainWindow::MainWindow(QApplication *qApp, QWidget* parent, const char* name )
	: QWidget( parent, name, WStyle_Customize | WStyle_NoBorder )
{
  info = new InfoGui(qApp, this);

  video_width = config->readInt("video_width");
  video_height = config->readInt("video_height");

  int resolution_w = config->readInt("pixel_width");
  int resolution_h = config->readInt("pixel_height");

  unit = ((float)resolution_w / (float)(config->readFloat("screensize") * 3.1f));

  move(0,0);
  resize(resolution_w, resolution_h);

  // Load images
  pix_record = new QPixmap();
  pix_record->load( PIXMAP_RECORD );

  pix_stop = new QPixmap();
  pix_stop->load( PIXMAP_STOP );

  pix_freeze = new QPixmap();
  pix_freeze->load( PIXMAP_FREEZE );

  pix_unfreeze = new QPixmap();
  pix_unfreeze->load( PIXMAP_UNFREEZE );

  pix_cpr = new QPixmap();
  pix_cpr->load( PIXMAP_CPR );

  pix_snapshot = new QPixmap();
  pix_snapshot->load( PIXMAP_SNAPSHOT );

  pix_dummy = new QPixmap();
  pix_dummy->load( PIXMAP_DUMMY );
  
  pix_logo = new QPixmap();
  pix_logo->load( PIXMAP_LOGO_SMALL );

  timer = new QTimer(this);
  connect(timer, SIGNAL(timeout()), SLOT(redraw_edge()));
  rec_edge_counter = 0.0f;

  createGui();
  show();

  camera = new Camera(info);
  camera->connect(config->readString("server_addr")->c_str(), 
                  config->readInt("server_port"));

  recording = false;
  frozen = false;

  // Open the CPR Dialog
  cpr_clicked();

}

MainWindow::~MainWindow()
{
  delete camera;
  delete btn_cpr;
}

void MainWindow::createGui()
{
  // Layout widgets

  /*  _________________________________________________
   *(0) __________________________  |  ______________  |
   * | |        |        |        | | |              | |
   * |(1)       |        |        | |(2)             | |
   * | |        |        |        | | |              | |
   * | |        |        |        | | |              | |
   * | |        |        |        | | |______________| |
   * | |        |        |        | | |              | |
   * | |        |        |        | | |              | |
   * | |        |        |        | | |              | |
   * | |________|________|________| | |              | |
   * | |        |        |        | | |______________| |
   * | |________|________|________| | |              | |
   * | |        |        |        | | |              | |
   * | |________|________|________| | |              | |
   * | |        |        |        | | |              | |
   * | |________|________|________| | |______________| |
   * |______________________________|__________________|
   * |______________________________|__________________|
   */

	QGridLayout *g0 = new QGridLayout(this, 2, 2, 0, -1);
	QGridLayout *g1 = new QGridLayout(3, 4, -1);
  g0->addLayout(g1, 0, 0);

  QGroupBox *gb = new QGroupBox(this);
  //  gb->setRows(NUM_HISTORY);
  gb->setColumns(1);
  //  gb->setTitle("fisk");
  //	QGridLayout *g2 = new QGridLayout(1, NUM_HISTORY, -1);
  //	QVBoxLayout *g2 = new QVBoxLayout(this);
  //  g0->addLayout(g2, 0, 1);
  gb->setInsideMargin(25);
  gb->setFlat(true);
  g0->addWidget(gb, 0, 1);

  img_recedge = new QLabel(this);
  img_recedge->setBackgroundColor(QColor(160,160,160));
  img_recedge->setFixedSize(video_width + 20, video_height + 20);
  
  img_live = new VideoWidget(img_recedge);
  //  img_live->setErasePixmap( *pix_dummy );
  img_live->setFixedSize(video_width, video_height);
  img_live->move(10,10);
  g1->addMultiCellWidget ( img_recedge, 0, 0, 0, 2, Qt::AlignHCenter);

  // CPR/NAME LABEL + CPR button
  lbl_cpr = createLabel("", 18, 3);
  g1->addMultiCellWidget ( lbl_cpr, 1, 1, 0, 1);

  btn_cpr = createButton("", 8, 3);
  btn_cpr->setFocus();
  btn_cpr->setPixmap(*pix_cpr);
  QObject::connect( btn_cpr, SIGNAL(clicked()), this, SLOT(cpr_clicked()) );
  // Will also be connected in the MGUI code
  g1->addWidget(btn_cpr, 1, 2);

  lbl_name = createLabel("", 18, 2);
  g1->addMultiCellWidget ( lbl_name, 2, 2, 0, 2);

  // Rec + Shot + Freeze buttons
  btn_rec = createButton("", 8, 3);
  btn_rec->setPixmap(*pix_record);
  QObject::connect( btn_rec, SIGNAL(clicked()), this, SLOT(rec_clicked()) );
  g1->addWidget(btn_rec, 3, 0);
  
  btn_shoot = createButton("", 8, 3);
  btn_shoot->setPixmap(*pix_snapshot);
  QObject::connect( btn_shoot, SIGNAL(clicked()), this, SLOT(shoot_clicked()) );
  g1->addWidget(btn_shoot, 3, 1);
  
  btn_freeze = createButton("", 8, 3);
  btn_freeze->setPixmap(*pix_freeze);
  QObject::connect( btn_freeze, SIGNAL(clicked()), this, SLOT(freeze_clicked()) );
  g1->addWidget(btn_freeze, 3, 2);
  
  // History widgets
  for(int i = 0; i < NUM_HISTORY; i++) {
    img_history[i] = new QLabel(gb);
    img_history[i]->setPixmap(*pix_dummy);
    img_history[i]->setFixedSize(240,192);
    //    g2->addWidget(img_history[i], i, 0, Qt::AlignHCenter & Qt::AlignVCenter);
    //    g2->addWidget(img_history[i]);
  }

  // Statusbar
  status = new QStatusBar(this);
  status->setSizeGripEnabled(FALSE);
  g0->addMultiCellWidget(status, 4, 4, 0, 1);

  lbl_version = createLabel("MIaV-Grab v" VERSION, 18, 1);
  lbl_version->setFixedWidth(300);
  status->addWidget(lbl_version, 0, TRUE);

  status->message( TXT_READY );
}

#define GREY 160
#define SPEED 0.07f
void MainWindow::redraw_edge()
{
  rec_edge_counter += SPEED;
  float val = fabs(sin(rec_edge_counter));
  img_recedge->setBackgroundColor(QColor((int) ((255 - GREY) * val + GREY),
                                         (int) (GREY - (GREY * val)),
                                         (int) (GREY - (GREY * val))));
}

QPushButton *MainWindow::createButton(char *caption, int width, int height)
{
  QPushButton *btn = new QPushButton(caption, this);
  btn->setFont( QFont( "Arial", (int)(unit * height / 2), QFont::Bold ) );
  btn->setFixedHeight((int)(unit * height));
  return btn;
}

QLabel *MainWindow::createLabel(char *caption, int width, int height)
{
  QLabel *lbl = new QLabel(caption, this);
  lbl->setFont( QFont( "Arial", (int)(unit * height / 2), (height>1)?QFont::Bold:QFont::Normal ) );
  lbl->setFixedHeight((int)(unit * height));
  return lbl;
}

void MainWindow::message(char *msg)
{
  //  lbl_status->setText(msg);
  status->message(msg);
}

void MainWindow::cpr_clicked()
{
  char oldcpr[256];
  char oldname[256];

  // If recording, stop recording before changingcpr
  if(recording) {
    MessageBox(this, 
               TXT_STOP_RECORDING_TITLE, 
               TXT_STOP_RECORDING, 
               TYPE_OK, 
               ICON_WARNING).exec();
    return;
  }


  // Save CPR and name, from the labels.
  strcpy(oldname, lbl_name->text().ascii());
  strcpy(oldcpr, lbl_cpr->text().ascii());

  // Create and call the CPRQueryDialog.
  CPRQueryDialog dlg(lbl_cpr, lbl_name, this, TXT_CPRDLG_TITLE, status);

  if(dlg.exec() == 0) {
    // Restore old CPR and name, in the labels. 
    lbl_name->setText(oldname);
    lbl_cpr->setText(oldcpr);
  } else {
    // Change CPR camera.
    camera->setCpr((char*)lbl_cpr->text().ascii());
  }
}

void MainWindow::rec_clicked()
{
  if(!recording) {
    recording = 1;
    // Start flashing the edge
    rec_edge_counter = 0.0f;
    timer->start(100);
    btn_rec->setPixmap(*pix_stop);
    camera->start();
  } else {
    switch(MessageBox(this, 
                      TXT_ASK_SAVE_TITLE, 
                      TXT_ASK_SAVE, 
                      TYPE_YES_NO_MAYBE_CANCEL, 
                      ICON_QUESTION).exec()) {
    case MSG_YES:
      recording = 0;
      camera->stop(SAVE);
      timer->stop();
      img_recedge->setBackgroundColor(QColor(160,160,160));
      btn_rec->setPixmap(*pix_record);
      break;

    case MSG_NO:
      recording = 0;
      camera->stop(DELETE);
      timer->stop();
      img_recedge->setBackgroundColor(QColor(160,160,160));
      btn_rec->setPixmap(*pix_record);
      break;

    case MSG_MAYBE:
      recording = 0;
      camera->stop(LATER);
      timer->stop();
      img_recedge->setBackgroundColor(QColor(160,160,160));
      btn_rec->setPixmap(*pix_record);
      break;

    case MSG_CANCEL:
      break;
    }
  }
}

void MainWindow::shoot_clicked()
{
  //  unsigned char pixels[720*576*3];

  QImage image(720, 576, 32);

  camera->snapshot(image.bits());

  image = image.smoothScale(img_history[0]->width(), img_history[0]->height());

  QPixmap pixmap;
  for(int cnt = (NUM_HISTORY-1); cnt > 0; cnt--) {
    pixmap = *img_history[cnt-1]->pixmap();
    img_history[cnt]->setPixmap(pixmap);
  }
  img_history[0]->setPixmap(image);

  if(frozen) {
    camera->unfreeze();
    btn_freeze->setPixmap(*pix_freeze);
    btn_freeze->setOn(false);
    frozen = false;
  }
}

void MainWindow::freeze_clicked()
{
  if(frozen) {
    camera->unfreeze();
    btn_freeze->setPixmap(*pix_freeze);
    btn_freeze->setOn(false);
    frozen = false;
  } else {
    camera->freeze();
    btn_freeze->setPixmap(*pix_unfreeze);
    btn_freeze->setOn(true);
    frozen = true;
  }
}

#endif /*USE_GUI*/