/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set et sw=2 ts=2: */
/***************************************************************************
 *            viewer.cc
 *
 *  Mon Aug 17 08:53:29 CEST 2009
 *  Copyright 2009 Bent Bisballe Nyeng
 *  deva@aasimon.org
 ****************************************************************************/

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

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFile>
#include <QScrollBar>

#include <QSettings>
#include <QTextCodec>

#ifdef WITH_FROGS
Status::Status()
{
  QVBoxLayout *vl = new QVBoxLayout();
  setLayout(vl);
  this->caption = new QLabel();
  vl->addWidget(this->caption);

  QHBoxLayout *ohl = new QHBoxLayout();
  ohl->setContentsMargins(0,0,0,0);
  vl->addLayout(ohl);

  hl = new QHBoxLayout();
  hl->setContentsMargins(0,0,0,0);
  ohl->addLayout(hl);

  ohl->addStretch();
}

void Status::setCaption(QString caption)
{
  this->caption->setText(caption + ":");
}

void Status::setStatus(QString macro, QString caption, bool done)
{
  if(icons.find(macro) == icons.end()) {
    QLabel *icon = new QLabel();
    icon->setContentsMargins(0,0,0,0);
    icon->setMargin(0);
    icon->setIndent(0);
    icon->setWhatsThis(caption);
    icon->setToolTip(caption);
    icons[macro] = icon;
    hl->addWidget(icon);
  }

  icons[macro]->setPixmap(QPixmap(done?":/icons/done.png":":icons/undone.png"));
}
#endif

extern QFont *fixedfont; // Defined in pracro.cc

Viewer::Viewer(QString cpr, QString templs, QString host, quint16 port,
               QString user, QString journalpath)
  : QWidget(NULL)
{
  this->templs = templs.split(QRegExp("\\W+"), QString::SkipEmptyParts);

  connect(&updatetimer, SIGNAL(timeout()), this, SLOT(update()));

#ifdef WITH_FROGS
  netcom = new NetCom(host, port);
  netcom->user = user;
  netcom->patientid = cpr;
  netcom->sessionid = "";
  netcom->initConnection();
#endif

  host = host; port = port; user = user;
  this->cpr = cpr;
  this->journalpath = journalpath;
  updatetimer.start(10000); // Trigger every 10 seconds

  QVBoxLayout *l = new QVBoxLayout();
  setLayout(l);

#ifdef WITH_FROGS
  QStringList::iterator ti = this->templs.begin();
  while(ti != this->templs.end()) {
    Status *s = new Status();
    l->addWidget(s);
    statuses[*ti] = s;
    ti++;
  }
#endif

  journal = new QTextEdit();
  journal->setReadOnly(true);
  journal->setFont(*fixedfont);
  l->addWidget(journal);

  init();
  update();
}

Viewer::~Viewer()
{
#ifdef WITH_FROGS
  delete netcom;
#endif
  delete journal;
}

extern QWidget *viewer;
void Viewer::closeEvent(QCloseEvent *)
{
  QSettings settings("Aasimon.org", "Pracro");

  settings.beginGroup("ViewerWindow");
  settings.setValue("size", size());
  settings.setValue("pos", pos());
  settings.endGroup();
  viewer = NULL;

  updatetimer.stop();

#ifdef WITH_FROGS
  netcom->discard(); // Make sure sessionid is removed.
#endif
}

void Viewer::init()
{
  QSettings settings("Aasimon.org", "Pracro");

  settings.beginGroup("ViewerWindow");
  resize(settings.value("size", QSize(700, 800)).toSize());
  move(settings.value("pos", QPoint(0, 0)).toPoint());
  settings.endGroup();
}


void Viewer::update()
{
#ifdef WITH_FROGS
  QStringList::iterator ti = templs.begin();
  while(ti != templs.end()) {
    QDomDocument xml_doc = netcom->send(*ti, "", false);

    QDomNodeList templates = xml_doc.documentElement().childNodes();
    QDomNode templatenode = templates.at(0); // There can be only one! (Swush, flomp)
    QDomElement templateelement = templatenode.toElement();
    
    statuses[*ti]->setCaption(templateelement.attribute("title"));

    QDomNodeList macronodes = templatenode.childNodes();
    for(int j = 0; j < macronodes.count(); j++) {
      QDomNode macronode = macronodes.at(j);
      QDomElement macroelement = macronode.toElement();
      
      if(macroelement.tagName() != "macro") continue;
      
      if(macroelement.attribute("static") == "true") continue;
      
      QString macroname = macroelement.attribute("name");
      QString caption = macroelement.attribute("caption");
      QString completed = macroelement.attribute("completed");
      
      statuses[*ti]->setStatus(macroname, caption, completed == "true");
    }

    ti++;  
  }
#endif

  // re-read journal file:
  QString crypt;
  for(int i = cpr.length() - 1; i >= 0; i--) {
    if(i == 2 || i == 3) continue;
    crypt += QString::number(9 - cpr.mid(i, 1).toInt());
  }
  
  QString filename = journalpath + "/" + cpr.mid(2,2) + "/" + crypt + "/JOURNAL.TXT";
  //  filename = "/home/senator/JOURNAL.TXT";

  QTextCodec *cp850 = QTextCodec::codecForName("cp850");
  if(!cp850) {
    printf("Could not find decoder for cp850!\n");
  }

  QFile jfile(filename);
  jfile.open(QIODevice::ReadOnly);
  QByteArray jcp850 = jfile.readAll();
  QString j = cp850->toUnicode(jcp850);

  QString jstrip;
  for(int i = 0; i < j.length(); i++) {
    if(j[i] != '�') jstrip += j[i]; // Remove end of line symbols.
  }

  if(journal->toPlainText() != jstrip) {
    int pos = journal->verticalScrollBar()->value();
    journal->setPlainText(jstrip);
    journal->verticalScrollBar()->setValue(pos);
  }
}