/* hintdb.c
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2012 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "hintdb.hh"
#include "wconfig.h"
#include "simplelist.hh"
#include "wchotkey.hh"
#include "wcbutton.hh"
#include "functionproto.h"
#include "worker.h"
#include "wcdoubleshortkey.hh"
#include <fstream>
#include "scriptop.h"

HintDBFlagProducer::HintDBFlagProducer( WConfig &wconf ) : m_wconfig( wconf )
{
}

std::string HintDBFlagProducer::getFlagReplacement( const std::string &flag )
{
    if ( hasFlag( flag ) ) return m_cache[flag];

    return "";
}

/* this functions checks if the fp is a script op and contains the op as eval command */
static bool checkScriptOp( const std::shared_ptr< FunctionProto > &fp, const std::string &op )
{
    auto sop = std::dynamic_pointer_cast< ScriptOp >( fp );

    if ( sop ) { 
        if ( sop->getType() == ScriptOp::SCRIPT_EVALCOMMAND &&
             AGUIXUtils::starts_with( sop->getCommandStr(),
                                      op ) ) {
            return true;
        }
    }

    return false;
}

bool HintDBFlagProducer::hasFlag( const std::string &str )
{
    if ( m_cache.count( str ) > 0 ) return true;

    std::string res;
    std::string op, info;

    std::vector< std::string > flag_components;

    AGUIXUtils::split_string( flag_components,
                              str, '-' );

    if ( flag_components.size() == 2 && flag_components[1] == "key" ) {
        op = flag_components[0];
        info = "key";
    } else if ( flag_components.size() == 2 && flag_components[1] == "descr" ) {
        op = flag_components[0];
        info = "descr";
    } else if ( flag_components.size() == 2 && flag_components[1] == "keyall" ) {
        op = flag_components[0];
        info = "keyall";
    } else {
        op = str;
        info = "key";
    }

    if ( info == "key" || info == "keyall" ) {
        List *hkeys = m_wconfig.getHotkeys();

        if ( hkeys ) {
            int id = hkeys->initEnum();
            WCHotkey *h1 = (WCHotkey*)hkeys->getFirstElement( id );

            while ( h1 != NULL && ( res.empty() || info == "keyall" ) ) {
                auto coms = h1->getComs();

                for ( auto &fp : coms ) {
                    if ( ! ( res.empty() || info == "keyall" ) ) {
                        break;
                    }

                    if ( fp->isName( op.c_str() ) ||
                         checkScriptOp( fp, op ) ) {
                        List *doublekeys = h1->getDoubleKeys();

                        if ( doublekeys ) {
                            int id_k = doublekeys->initEnum();

                            WCDoubleShortkey *dk = (WCDoubleShortkey*)doublekeys->getFirstElement( id_k );

                            while ( dk != NULL && ( res.empty() || info == "keyall" ) ) {
                                std::string str1 = dk->getName( Worker::getAGUIX() );

                                if ( res.empty() ) {
                                    res = str1;
                                } else {
                                    res += ", ";
                                    res += str1;
                                }

                                dk = (WCDoubleShortkey*)doublekeys->getNextElement( id_k );
                            }
                            doublekeys->closeEnum( id_k );
                        }                
                    }
                }

                h1 = (WCHotkey*)hkeys->getNextElement( id );
            }
            hkeys->closeEnum( id );
        }

        if ( res.empty() ) {
            List *buttons = m_wconfig.getButtons();

            if ( buttons ) {
                int id = buttons->initEnum();
                WCButton *b1 = (WCButton*)buttons->getFirstElement( id );

                while ( b1 != NULL && ( res.empty() || info == "keyall" ) ) {
                    auto coms = b1->getComs();

                    for ( auto &fp : coms ) {
                        if ( ! ( res.empty() || info == "keyall" ) ) {
                            break;
                        }

                        if ( fp->isName( op.c_str() ) ||
                             checkScriptOp( fp, op ) ) {
                            List *doublekeys = b1->getDoubleKeys();

                            if ( doublekeys ) {
                                int id_k = doublekeys->initEnum();

                                WCDoubleShortkey *dk = (WCDoubleShortkey*)doublekeys->getFirstElement( id_k );

                                while ( dk != NULL && ( res.empty() || info == "keyall" ) ) {
                                    std::string str1 = dk->getName( Worker::getAGUIX() );

                                    if ( res.empty() ) {
                                        res = str1;
                                    } else {
                                        res += ", ";
                                        res += str1;
                                    }

                                    dk = (WCDoubleShortkey*)doublekeys->getNextElement( id_k );
                                }
                                doublekeys->closeEnum( id_k );
                            }                
                        }
                    }

                    b1 = (WCButton*)buttons->getNextElement( id );
                }
                buttons->closeEnum( id );
            }
        }
    } else if ( info == "descr" ) {
        for ( int i = 0; i < Worker::getNrOfCommands(); i++ ) {
            auto fp = Worker::getCommand4ID( i );

            if ( fp ) {
                if ( fp->isName( op.c_str() ) ) {
                    res = fp->getDescription();
                }
            }
        }
    }

    if ( ! res.empty() ) {
        m_cache[str] = res;
        return true;
    }

    return false;
}

HintDB::HintDB( const std::string &file,
                WConfig &wconf ) : m_file( file ),
                                   m_wconfig( wconf )
{
    m_flag_producer = std::make_shared< HintDBFlagProducer >( m_wconfig );
    m_flag_replacer = std::make_shared< FlagReplacer >( m_flag_producer );

    read_db();
}

HintDB::~HintDB()
{
    m_flag_replacer = NULL;
    m_flag_producer = NULL;
}

std::string HintDB::getNextHint()
{
    int r = rand();

    if ( m_hint_db.empty() ) return "";

    std::string entry = m_hint_db.at( r % m_hint_db.size() );

    std::vector< std::string > entry_components;

    AGUIXUtils::split_string( entry_components,
                              entry, '|' );

    if ( entry_components.size() > 0 ) {
        std::string res = m_flag_replacer->replaceFlags( entry_components[0] );

        if ( m_flag_replacer->failed_flag_replacements() > 0 ) {
            if ( entry_components.size() > 1 ) {
                res = m_flag_replacer->replaceFlags( entry_components[1] );
            } else {
                res = "";
            }
        }

        return res;
    } else return "";
}

void HintDB::read_db()
{
    m_hint_db.clear();

    std::ifstream ifile( m_file.c_str() );
    std::string line;
    
    if ( ifile.is_open() ) {
        while ( std::getline( ifile, line ) ) {
            if ( ! line.empty() && line[0] != '#' ) {
                m_hint_db.push_back( line );
            }
        }
    }
}
