/*
    This program 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.
*/

/*
  Copyright (C) 2005 Francois Chazal <neptune3k@free.fr>
  Copyright (C) 2006-2007 Eike Hein <hein@kde.org>
*/


#include "terminal.h"
#include "terminal.moc"


int Terminal::available_terminal_id = 0;

Terminal::Terminal(TQWidget* parent, const char* name) : TQObject(parent, name)
{
    terminal_id = available_terminal_id;
    available_terminal_id++;

    setenv("DCOP_YAKUAKE_TERMINAL", TQString::number(terminal_id).ascii(), 1);
    putenv((char*)"COLORTERM="); // Trigger mc's color detection.

    KLibFactory* factory = NULL;

    terminal_part = NULL;
    terminal_title = "";
    terminal_widget = NULL;
    terminal_interface = NULL;

    if ((factory = KLibLoader::self()->factory("libkonsolepart")) != NULL)
    {
        TQStringList args = TQStringList();
        args.append(TQString("Terminal-") + TQString::number(terminal_id));
        terminal_part = (KParts::Part *) (factory->create(parent, 0, "KParts::Part", args));
    }

    if (terminal_part != NULL)
    {
        terminal_widget = terminal_part->widget();
        terminal_widget->setFocusPolicy(TQWidget::WheelFocus);
        terminal_interface = (TerminalInterface *) (terminal_part->tqt_cast("TerminalInterface"));

        connect(terminal_part, TQ_SIGNAL(destroyed()), this, TQ_SLOT(deleteLater()));
        connect(terminal_part, TQ_SIGNAL(setWindowCaption(const TQString &)), this, TQ_SLOT(slotUpdateSessionTitle(const TQString &)));
    }
}

Terminal::~Terminal()
{
    emit destroyed(terminal_id);
}

TQWidget* Terminal::widget()
{
    return terminal_widget;
}

TerminalInterface* Terminal::terminal()
{
    return terminal_interface;
}

const TQString Terminal::title()
{
    return terminal_title;
}

void Terminal::setTitle(const TQString& title)
{
    slotUpdateSessionTitle(title);
}

void Terminal::slotUpdateSessionTitle(const TQString& title)
{
    terminal_title = title;

    // Remove trailing " -" from the caption. If needed this is
    // handled later in TitleBar.
    if (terminal_title.endsWith(" - "))
        terminal_title.truncate(terminal_title.length() - 3);

    emit titleChanged(terminal_widget, terminal_title);
}
