/* ====================================================================
 * Copyright (c) 2003-2007, 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.h"
#include "settings/FontSettings.h"
#include "sublib/settings/LayoutSettings.h"
#include "util/iconvstream.h"

// qt
#include <QtGui/QPushButton>
#include <QtGui/QFileDialog>
#include <QtGui/QLayout>

// 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 )
{
  setName( "TextWindow" );
  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->setWordWrapMode(QTextOption::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()) );
    }
  }

  Settings s;
  resize( s.layout().getSize( name(), QSize(width(),height()) ) );
}

TextWindow::~TextWindow()
{
  Settings s;
  s.layout().setSize( name(), geometry().size() );
}

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 << (const char*)_text->text().utf8();
  o2.flush();
}

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