/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2014 Frederik Heber. All rights reserved.
 *
 *
 *   This file is part of MoleCuilder.
 *
 *    MoleCuilder 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.
 *
 *    MoleCuilder 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 MoleCuilder.  If not, see .
 */
/*
 * QtLogBox.cpp
 *
 *  Created on: Jun 19, 2014
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include "QtLogBox.hpp"
#include 
#include 
#include "CodePatterns/MemDebug.hpp"
#include "CodePatterns/Log.hpp"
#include "World.hpp"
QtLogBox::QtLogBox(QWidget * _parent) :
    QTextEdit (_parent),
    logbuf(std::cout, this)
{
  // don't edit the log
  setReadOnly(true);
//  setTextFormat(Qt::LogText);
}
QtLogBox::~QtLogBox()
{}
void QtLogBox::mousePressEvent(QMouseEvent *e)
{
  // translate the point under mouse into a cursor
  const QPoint &point = e->pos();
  QTextCursor cursor = cursorForPosition(point);
  // get the word under the pointer
  cursor.select(QTextCursor::WordUnderCursor);
  std::string atomname(cursor.selectedText().toStdString());
  // parse the word and check whether it is an atom name
  atomId_t id = getAtomIdForName(atomname);
  // select atom if id valid
  if (id != (atomId_t)-1) {
    if (!World::getInstance().isAtomSelected(id))
      World::getInstance().selectAtom(id);
    else
      World::getInstance().unselectAtom(id);
  }
  // recast event
  QTextEdit::mousePressEvent(e);
}
atomId_t QtLogBox::getAtomIdForName(const std::string &_name) const
{
  atomId_t id = -1;
  // find out where numbers begin
  std::string::const_iterator iter = _name.begin();
  for (; iter != _name.end(); ++iter) {
    if ((*iter < '0') || (*iter > '9'))
      continue;
    else
      break;
  }
  // translate numbers (correcting for printed numbers starting at 1, not 0)
  if (iter != _name.end()) {
    std::stringstream numbers(std::string(iter, _name.end()));
    numbers >> id;
    id -= 1;
  }
  return id;
}