/***************************************************************************
 *   Copyright (C) 2004 by Alexander Dymo                                  *
 *   cloudtemple@mksat.net                                                 *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/
#include "docchmplugin.h"

#include <kurl.h>
#include <tdeaboutdata.h>
#include <tdeconfig.h>
#include <tdelocale.h>
#include <tdelistview.h>
#include <tdeio/netaccess.h>
#include <iostream>
#include <fstream>
#include <tqvaluevector.h>
#include <kdevgenericfactory.h>
#include <kdevplugininfo.h>
#include <tqregexp.h>

#include "../../../../config.h"

static const KDevPluginInfo data("docchmplugin");
typedef KDevGenericFactory<DocCHMPlugin> DocCHMPluginFactory;
K_EXPORT_COMPONENT_FACTORY( libdocchmplugin, DocCHMPluginFactory(data) )

DocCHMPlugin::DocCHMPlugin(TQObject* parent, const char* name, TQStringList // args
                           )
    :DocumentationPlugin(DocCHMPluginFactory::instance()->config(), parent, name)
{
    autoSetup();
}

DocCHMPlugin::~DocCHMPlugin()
{
}


DocumentationCatalogItem* DocCHMPlugin::createCatalog(TDEListView* contents, TDEListViewItem *after, const TQString& title, const TQString& url)
{
    DocumentationCatalogItem *item = new DocumentationCatalogItem(this, contents, after, title);
    item->setURL(KURL(url));
    
    return item;
}

TQPair<KFile::Mode, TQString> DocCHMPlugin::catalogLocatorProps()
{
    return TQPair<KFile::Mode, TQString>(KFile::File, "*.chm");
}

TQString DocCHMPlugin::catalogTitle(const TQString& // url
                                   )
{
    return TQString();
}

TQString DocCHMPlugin::pluginName() const
{
    return i18n("CHM Documentation Collection");
}


TQString DocCHMPlugin::getSpecialData(const TQString& name, KURL url) {
    TQString ret = "";
    url.setProtocol("ms-its");
    
    url.addPath("/:" + name);
    TQString tmpFile;
    if( TDEIO::NetAccess::download( url, tmpFile, 0 ) )
    {
        std::filebuf fb;
        fb.open (tmpFile.ascii(), std::ios::in);
        std::istream is(&fb);
        char buf[5000] = " ";
        while(is.good()) {
            is.getline(buf, 5000);
            ret += buf; ret += "\n";
        }
        fb.close();
        TDEIO::NetAccess::removeTempFile( tmpFile );
    } else {
        kdDebug(9002) << "DocCHMPlugin::getSpecialData could not download data from " << url.url() << endl;
    }
    return ret;
}


///this currently is useless, because htdig cannot use tdeioslaves
TQStringList DocCHMPlugin::fullTextSearchLocations()
{
    //return TQStringList::split( '\n', getSpecialData("contents", m_url));
    return TQStringList();
}

bool DocCHMPlugin::needRefreshIndex(DocumentationCatalogItem* // item
                                    )
{
    return false;
}

void DocCHMPlugin::autoSetupPlugin()
{
    // Clear groups, to allow for re-autosetup calls
    config->deleteGroup("Index");
    config->deleteGroup("Index Settings");
    config->deleteGroup("Locations");
    config->deleteGroup("Search Settings");
    config->deleteGroup("TOC Settings");
    config->sync();
    return;
}

void DocCHMPlugin::createIndex(IndexBox* // index
                               , DocumentationCatalogItem* // item
                               )
{
    return;
}


static TDEListViewItem* chainEnd(TDEListViewItem *parent) {
    if(parent == 0) return 0;
    TDEListViewItem* ret = dynamic_cast<TDEListViewItem*>(parent->firstChild());
    if(ret == 0) return 0;
    while(ret->nextSibling() != 0) {
        ret = dynamic_cast<TDEListViewItem*>(ret->nextSibling());
    }
    return ret;
}

static TQString decodeHTML(const TQString& s) {
    TQRegExp rx(TQString::fromLatin1("&#(\\d+);|&nbsp;"));
    TQString out = s;
    int pos = rx.search(out);
    while(pos > -1) {
        TQString found = rx.cap(0);
        if(found != "&nbsp;") {
            out.replace(pos, found.length(), static_cast<char>(rx.cap(1).toInt()));
        }else{
            out.replace(pos, found.length(), " ");
        }
        pos = rx.search(out, pos+1);
    }
    return out;
}


void DocCHMPlugin::createTOC(DocumentationCatalogItem* item)
{
    TQStringList lines = TQStringList::split("\n", getSpecialData("catalog", item->url()) );
    if(lines.count() % 4 != 0) { kdDebug(9002) << "DocCHMPlugin::createTOC: wrong count of strings"; return;}
    
    TQValueVector<DocumentationItem*> items;
    items.push_back(item);
    for(TQStringList::Iterator it = lines.begin(); it != lines.end();) {
        bool ok1 = true, ok2 = true;
        int parent = (*it).toInt(&ok1);
        ++it;
        int current = (*it).toInt(&ok2);
        ++it;
        if(int(items.size()) != current || !ok1 || !ok2 || parent < 0 || parent >= int(items.size()) || current < 0 || current != int(items.size())) {
            kdDebug(9002) << "DocCHMPlugin::createTOC error while parsing output of ioslave" << endl;
            break;
        }
        
        TQString& name(*it);
        ++it;
        KURL url(*it);
        ++it;
        
        items.push_back(new DocumentationItem(
                DocumentationItem::Document, items[parent], chainEnd(items[parent]), decodeHTML(name)));
        items[current]->setURL(url);
        if(parent != 0) items[parent]->setType(DocumentationItem::Book);
    }
    

    return;
}

void DocCHMPlugin::setCatalogURL(DocumentationCatalogItem* item)
{
    KURL chmURL = item->url();
    chmURL.setProtocol("ms-its");
    chmURL.addPath("/");
    item->setURL(chmURL);
}

ProjectDocumentationPlugin *DocCHMPlugin::projectDocumentationPlugin(ProjectDocType type)
{
    if (type == APIDocs)
        return new ProjectDocumentationPlugin(this, type);
    return DocumentationPlugin::projectDocumentationPlugin(type);
}


#include "docchmplugin.moc"
