/***************************************************************************
 *   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                                                    *
 *   Richard Dale  <Richard_Dale@tipitina.demon.co.uk>                     *
 *   copyright (C) 2006-2014                                               *
 *   Umbrello UML Modeller Authors <umbrello-devel@kde.org>                *
 ***************************************************************************/

// own header
#include "rubycodeoperation.h"

// local includes
#include "debug_utils.h"
#include "rubyclassifiercodedocument.h"
#include "rubycodedocumentation.h"
#include "rubycodegenerator.h"
#include "uml.h"

// qt includes
#include <QRegExp>

RubyCodeOperation::RubyCodeOperation (RubyClassifierCodeDocument * doc, UMLOperation *parent, const QString & body, const QString & comment)
        : CodeOperation (doc, parent, body, comment)
{
    // lets not go with the default comment and instead use
    // full-blown ruby documentation object instead
    setComment(new RubyCodeDocumentation(doc));

    // these things never change..
    setOverallIndentationLevel(1);
}

RubyCodeOperation::~RubyCodeOperation()
{
}

// we basically want to update the doc and start text of this method
void RubyCodeOperation::updateMethodDeclaration()
{
    CodeDocument * doc = getParentDocument();
    RubyClassifierCodeDocument * rubydoc = dynamic_cast<RubyClassifierCodeDocument*>(doc);
    Q_ASSERT(rubydoc);
    UMLClassifier *c = rubydoc->getParentClassifier();
    UMLOperation * o = getParentOperation();
    bool isInterface = rubydoc->getParentClassifier()->isInterface();
    QString endLine = getNewLineEndingChars();

    // now, the starting text.
    //:UNUSED: QString strVis = o->visibility().toString();
    // no return type for constructors
    QString fixedReturn = RubyCodeGenerator::cppToRubyType(o->getTypeName());
    QString returnType = o->isConstructorOperation() ? QString() : (fixedReturn + QString(QLatin1String(" ")));
    QString methodName = o->name();

    QString RubyClassName = rubydoc->getRubyClassName(c->name());

    // Skip destructors, and operator methods which
    // can't be defined in ruby
    if (methodName.startsWith(QLatin1Char('~'))
         || QRegExp(QLatin1String("operator\\s*(=|--|\\+\\+|!=)$")).exactMatch(methodName))
    {
        getComment()->setText(QString());
        return;
    }

    if (RubyClassName == methodName) {
        methodName = QLatin1String("initialize");
    }

    methodName.remove(QRegExp(QLatin1String("operator\\s*")));
    methodName = methodName.mid(0, 1).toLower() + methodName.mid(1);

    QString paramStr;
    QStringList commentedParams;

    // assemble parameters
    UMLAttributeList list = getParentOperation()->getParmList();
    int nrofParam = list.count();
    int paramNum = 0;
    foreach (UMLAttribute* parm, list) {
        QString paramName = RubyCodeGenerator::cppToRubyName(parm->name());
        paramStr += paramName;
        if (! parm->getInitialValue().isEmpty()) {
            paramStr += QString(QLatin1String(" = ")) + RubyCodeGenerator::cppToRubyType(parm->getInitialValue());
        }
        paramNum++;

        if (paramNum != nrofParam)
            paramStr  += QLatin1String(", ");
    }

    QString startText;
    if (isInterface) {
        // Assume 'isInterface' means a module in Ruby, so
        // generate module methods
        startText = QLatin1String("def ") + RubyClassName + QLatin1Char('.') + methodName + QLatin1Char('(') + paramStr + QLatin1Char(')');
    } else {
        startText = QLatin1String("def ")+ methodName + QLatin1Char('(') + paramStr + QLatin1Char(')');
    }

    // startText += "";  ???
    setEndMethodText(QLatin1String("end"));

    setStartMethodText(startText);

    // Lastly, for text content generation, we fix the comment on the
    // operation, IF the codeop is autogenerated & currently empty
    QString comment = o->doc();

    if (comment.isEmpty()) {
        if (contentType() == CodeBlock::AutoGenerated) {
            UMLAttributeList parameters = o->getParmList();
            foreach (UMLAttribute* currentAtt, parameters) {
                comment += endLine + QLatin1String("* _") + currentAtt->name() + QLatin1String("_ ");
                comment += (QLatin1Char(' ') + currentAtt->doc().replace(QRegExp(QLatin1String("[\\n\\r]+[\\t ]*")), endLine + QLatin1String("  ")));
            }
            // add a returns statement too
            if (!returnType.isEmpty() && !QRegExp(QLatin1String("^void\\s*$")).exactMatch(returnType))
                comment += endLine + QLatin1String("* _returns_ ") + returnType + QLatin1Char(' ');
            getComment()->setText(comment);
        }
    } else {
        comment.replace(QRegExp(QLatin1String("[\\n\\r]+ *")), endLine);
        comment.replace(QRegExp(QLatin1String("[\\n\\r]+\\t*")), endLine);

        comment.replace(QLatin1String(" m_"), QLatin1String(" "));
        comment.replace(QRegExp(QLatin1String("\\s[npb](?=[A-Z])")), QLatin1String(" "));
        QRegExp re_params(QLatin1String("@param (\\w)(\\w*)"));
        int pos = re_params.indexIn(comment);
        while (pos != -1) {
            comment.replace(re_params.cap(0),
                            QString(QLatin1String("@param _")) + re_params.cap(1).toLower() + re_params.cap(2) + QLatin1Char('_'));
            commentedParams.append(re_params.cap(1).toLower() + re_params.cap(2));

            pos += re_params.matchedLength() + 3;
            pos = re_params.indexIn(comment, pos);
        }

        UMLAttributeList parameters = o->getParmList();
        foreach (UMLAttribute* currentAtt, parameters) {
            // Only write an individual @param entry if one hasn't been found already
            // in the main doc comment
            if (commentedParams.contains(RubyCodeGenerator::cppToRubyName(currentAtt->name())) == 0) {
                comment += (endLine + QLatin1String("@param _") + RubyCodeGenerator::cppToRubyName(currentAtt->name()) + QLatin1Char('_'));
                if (currentAtt->doc().isEmpty()) {
                    comment += (QLatin1Char(' ') + RubyCodeGenerator::cppToRubyType(currentAtt->getTypeName()));
                } else {
                    comment += (QLatin1Char(' ') + currentAtt->doc().replace(QRegExp(QLatin1String("[\\n\\r]+[\\t ]*")), endLine + QLatin1String("  ")));
                }
            }
        }

        comment.remove(QLatin1String("@ref "));
        comment.replace(QLatin1String("@param"), QLatin1String("*"));
        comment.replace(QLatin1String("@return"), QLatin1String("* _returns_"));

        // All lines after the first one starting with '*' in the doc comment
        // must be indented correctly. If they aren't a list
        // item starting with '*', then indent the text with
        // two spaces, '  ', to line up with the list item.
        pos = comment.indexOf(endLine + QLatin1Char('*'));
        if (pos != -1) {
            pos += endLine.length() + 1;
            pos = comment.indexOf(endLine, pos);
        }

        while (pos > 0) {
            pos += endLine.length();
            if (comment[pos] != QLatin1Char('*')) {
                comment.insert(pos, QLatin1String("  "));
                pos += 2;
            }

            pos = comment.indexOf(endLine, pos);
        }

        QString typeStr = RubyCodeGenerator::cppToRubyType(o->getTypeName());
        if (!typeStr.isEmpty()
                && !QRegExp(QLatin1String("^void\\s*$")).exactMatch(typeStr)
                && comment.contains(QLatin1String("_returns_")) == 0)
        {
            comment += endLine + QLatin1String("* _returns_ ") + typeStr;
        }

        getComment()->setText(comment);
    }

    // In Java, for interfaces..we DON'T write out non-public
    // method declarations. And for Ruby modules?
    if (isInterface) {
        UMLOperation * o = getParentOperation();
        if (o->visibility() != Uml::Visibility::Public)
            setWriteOutText(false);
    }

}

int RubyCodeOperation::lastEditableLine()
{
    ClassifierCodeDocument * doc = dynamic_cast<ClassifierCodeDocument*>(getParentDocument());

    // Check for dynamic casting failure
    if (doc == 0)
    {
        uError() << "doc: invalid dynamic cast";
        return -1;
    }

    if (doc->parentIsInterface())
        return -1; // very last line is NOT editable as its a one-line declaration w/ no body in
    // an interface.
    return 0;
}

