/* ====================================================================
 * Copyright (c) 2003-2006, Martin Hauner
 *                          http://subcommander.tigris.org
 *
 * Subcommander is licensed as described in the file doc/COPYING, which
 * you should have received as part of this distribution.
 * ====================================================================
 */

// sc
#include "config.h"
#include "TextWindow.h"
#include "TextEdit.h"
#include "settings/FontSettings.h"
#include "util/iconvstream.h"

// qt
#include <qpushbutton.h>
#include <qfiledialog.h>
#include <qlayout.h>

// sys
#include <fstream>



Qt::WFlags TextWindowFlags = Qt::WStyle_Customize | Qt::WType_TopLevel
  | Qt::WStyle_MinMax  | Qt::WStyle_NormalBorder | Qt::WStyle_Title
  | Qt::WStyle_SysMenu | Qt::WDestructiveClose;


TextWindow::TextWindow( const QString& title, FontSettings* fs,
  QWidget *parent )
: super( parent, 0, TextWindowFlags )
{
  setCaption( _q("subcommander:") + title );

  QVBoxLayout *vbl = new QVBoxLayout(this,5,8);
  vbl->setSpacing(10);
  {
    _text = new TextEdit(this);

    QFont font = fs->getEditorFont();
    _text->setFont( font );
    _text->setWordWrap(QTextEdit::NoWrap);
    vbl->addWidget(_text);

    QHBoxLayout* hu = new QHBoxLayout;
    vbl->addLayout(hu);
    {
      // eats extra space, so the buttons keep their size
      hu->addStretch(1); 

      _save = new QPushButton(this);
      _save->setText( _q("&Save As") );
      _save->setDefault(true);
      hu->addWidget(_save);
      _close = new QPushButton(this);
      _close->setText( _q("&Close") );
      hu->addWidget(_close);

      connect( _save, SIGNAL(clicked()), SLOT(save()) );
      connect( _close, SIGNAL(clicked()), SLOT(close()) );
    }
  }

  resize( 750, 600 );
}

TextWindow::~TextWindow()
{
}

void TextWindow::setText( const QString& text )
{
  _text->setText(text);
}

void TextWindow::loadText( const QString& file )
{
  std::ifstream f1( file, std::ios_base::binary|std::ios_base::in );
  iconvistream  f2( f1, "*", "utf-8" );
      
  sc::String content;

  while( ! f2.eof() )
  {
    char buf[1025] = {};
    f2.read( buf, sizeof(buf)-1 );
    content += buf;
  }

  QString qcontent = QString::fromUtf8(content);
  setText(qcontent);
}

void TextWindow::save()
{
  QString sel = QFileDialog::getSaveFileName( "*.patch", "", this, "", _q("save as...") );

  if( sel.isNull() )
  {
    return;
  }

  std::ofstream o1( sel, std::ios_base::binary );
  iconvostream  o2( o1, "utf-8", "*" );

  o2 << _text->text().utf8();
  o2.flush();
}

void TextWindow::close()
{
  delete this;
}


syntax highlighted by Code2HTML, v. 0.9.1