//
// C++ Implementation: c6textedit
//
// Description:
//
//
// Author: Giorgio A. <openc6@hotmail.com>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "c6textedit.h"
#include <qregexp.h>

const char *linkList[] =
    {
        "HTTP://","FTP://","HTTPS://","NEWS://","WWW.","FTP.","ROOM://","NICK://","C6CMD://",0
    };

C6TextEdit::C6TextEdit(QWidget *parent, int x,int y,int width,int height) : QTextEdit(parent)
{
    setTextFormat(RichText);
    setWordWrap(WidgetWidth);
    setWrapPolicy(AtWordOrDocumentBoundary);
    setLinkUnderline(true);
    setReadOnly(true);
    setGeometry(QRect(x,y,width,height));
    setFocusPolicy(QTextEdit::NoFocus );
    setMargin(1);
    setHScrollBarMode(QTextEdit::AlwaysOff);
}


C6TextEdit::~C6TextEdit()
{}

void C6TextEdit::contentsMouseMoveEvent(QMouseEvent * e)
{
    QString url = anchorAt(e->pos());

    if (!url.isNull())
    {
        viewport()->setCursor(QCursor(PointingHandCursor));
    }
    else
    {
        viewport()->unsetCursor();
    }

    QTextEdit::contentsMouseMoveEvent(e);
}

void C6TextEdit::contentsMouseDoubleClickEvent(QMouseEvent * e)
{
    QString url = anchorAt(e->pos());

    QTextEdit::contentsMouseMoveEvent(e);

    if (!url.isNull())
    {      
        emit execUrl(url);
    }      
}

void C6TextEdit::serviceMessage(QString text,bool time)
{
    if (time == true)
    {
        text.prepend("["+QTime::currentTime(Qt::LocalTime).toString()+"]&nbsp;");
    }

    append("<smessage>"+text+"</smessage>");
}


/*!
    \fn C6TextEdit::processRich()
 */
QString C6TextEdit::processRichText(QString text)
{
    int id = 0;
    int end_pos = 0;
    QString tmp;
    QString str;
    QString out_str;
    bool found = false;
    int pos = 0;
    int main_pos = 0;

    while (main_pos < static_cast<int>(text.length()))
    {
        id = 0;
        found = false;

        while ((linkList[id] != 0) && !found)
        {
            tmp = QString(linkList[id]);
            pos = text.find(tmp,main_pos,FALSE);

            if (pos >=0)
            {
                if ((pos > 0) && (pos > main_pos))
                {
                    out_str.append(processEmail(text.mid(main_pos,pos-main_pos)));
                }

                if (tmp.compare("ROOM://") != 0)
                {
                    end_pos = text.find(QChar(' '),pos);
                }
                else
                {
                    end_pos = text.find(QChar('\"'),pos);
                    text.insert(end_pos+1," :");
                }

                if (end_pos == -1)
                {
                    end_pos = text.length();
                }

                str = text.mid(pos,end_pos-pos);

                if (tmp.compare("NICK://") == 0)
                {
                    QString nick = str.mid(7,str.length());    
                    out_str.append("<a href=\""+nick+"\">"+nick+"</a>"); 
                }
                else
                {               
                    if (tmp.compare("C6CMD://") == 0)           
                    {
                        if (str.contains("Accept") == true)        
                        {
                            int begin = str.find("Type=",0,FALSE) + 5;    
                            int end = str.find(QChar('&'),begin,FALSE);
                            QString type = str.mid(begin,end-begin);   
                            QString value = (str.contains("YES") == true) ? "Si" : "No";   
                            out_str.append(" <a href=\""+type+"="+value+"\">"+value+"</a>"); 
                        }
                    }                  
                    else
                    {
                        out_str.append("<a href=\""+str+"\">"+str+"</a>");
                    }
                }
                    
                main_pos = end_pos;
                found = true;
            }
            id++;
        }

        if (!found)
        {
            out_str.append(processEmail(text.mid(main_pos,text.length()-main_pos)));
            main_pos = text.length();
        }
    }

    id = 0;
    /* subst emoticons */
    while (id < C6Smiley::MAXFACCINE)
    {
        tmp = C6Smiley::getSmileyText(id);
        out_str.replace(tmp,"<img source=\""+tmp+"\" width=18 height=18>",FALSE);
        id++;
    }

    return(out_str);
}

/*!
    \fn C6TextEdit::processEmail(QString text)
 */
QString C6TextEdit::processEmail(QString const & text)
{
    int main_pos = 0;
    QString out_str;
    QString email_str;
    QRegExp searchExp("[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)");

    int pos = 0;
    do
    {
        main_pos = pos;
        pos = searchExp.search(text,pos);

        if (pos >=0)
        {
            out_str.append(text.mid(main_pos,pos-main_pos));
            email_str = searchExp.cap();
            out_str.append("<a href=\"mailto:"+email_str+"\">"+email_str+"</a>");
            pos += searchExp.matchedLength();
        }
        else
        {
            out_str.append(text.mid(main_pos,text.length()-main_pos));
        }
    }
    while (pos != -1);

    return(out_str);
}



/*!
    \fn C6TextEdit::showMyText(QString &nick,QString &text)
 */
void C6TextEdit::showMyText(QString const &nick,QString const &text,bool time)
{
    QString winText = text;        
   
    const char winEuroHex[2]={0x80,0};     
    const QChar unicodeEuro = 0x20ac;    
    winText.replace(QString(winEuroHex),unicodeEuro);          
    
    QString tmp = "<mynick>";

    if (time == true)
    {      
        tmp += "["+QTime::currentTime(Qt::LocalTime).toString()+"]&nbsp;";
    }      

    tmp +=nick+"</mynick>"+"<mymessage>&nbsp;-&nbsp;"+processRichText(winText)+"</mymessage>";

    append(tmp);
}


/*!
    \fn C6TextEdit::showOtherText(QString& nick,QString &text)
 */
void C6TextEdit::showOtherText(QString const & nick,QString const &text,bool time)
{
    QString winText = text;        
   
    const char winEuroHex[2]={0x80,0};     
    const QChar unicodeEuro = 0x20ac;    
    winText.replace(QString(winEuroHex),unicodeEuro);       
    
    QString tmp = "<netfnick>";

    if (time == true)
    {
        tmp+="["+QTime::currentTime(Qt::LocalTime).toString()+"]&nbsp;";
    }

    tmp +=nick+"</netfnick>&nbsp;-&nbsp;<netfmessage>"+processRichText(winText)+"</netfmessage>";

    append(tmp);
}

#include "c6textedit.moc"
