/* flagreplacer.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2006-2021 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 "flagreplacer.hh"
#include "aguix/lowlevelfunc.h"
#include "aguix/awindow.h"
#include "aguix/acontainer.h"
#include "aguix/button.h"
#include "aguix/fieldlistview.h"
#include "worker.h"
#include "worker_locale.h"

FlagReplacer::FlagReplacer( std::shared_ptr< FlagProducer > flagstore )
    : m_flagstore( flagstore ),
      m_replace_errors( 0 )
{
}

FlagReplacer::~FlagReplacer()
{
}

std::string FlagReplacer::replaceFlags( const std::string &str, bool quote )
{
  char ch;
  int spos = 0, bracketcount = 0;
  int mode = 0;
  bool ende;
  bool force_noquoting;
  std::string dstr, flagbuf;

  const char *sstr = str.c_str();

  m_replace_errors = 0;

  //TODO utf8 improvements
  for ( ende = false; ende == false; ) {
    ch = sstr[spos++];
    if ( ch == '\0' ) break;
    switch ( mode ) {
      case 1:
        // we are in a open bracket and waiting for close bracket
        if ( ch == '{' ) {
          // other flag, perhaps useless, but perhaps it is in a String-requester
          // in any case just overtake it in the buffer
          flagbuf += ch;
          bracketcount++;
        } else if ( ch == '}' ) {
          // a closeing bracket
          if ( bracketcount > 1 ) {
            // this is a bracket in the bracket
            flagbuf += ch;
          } else {
            // this is the awaited closebracket
            // now flagbuf contains a flag which must be parsed
            mode = 3;
          }
          bracketcount--;
        } else if ( ch == '\\' ) {
          // backslash are only resolved on toplevel (bracketcount==0)
          // so overtake also this
          flagbuf += ch;
          mode = 4;
        } else {
          flagbuf += ch;
        }
        break;
      case 2:
        dstr += ch;
        mode = 0;
        break;
      case 4:
        flagbuf += ch;
        mode = 1;
        break;
      default:
        // we are in no bracket
        if ( ch == '\\' ) {
          // next character is protected and will be overtaken
          mode = 2;
        } else if ( ch != '{' ) {
          // a normal character
          dstr += ch;
        } else {
          mode = 1;
          bracketcount++;
          flagbuf = "";
        }
        break;
    }
    if ( mode == 3 ) {
      const char *buf1;
      if ( flagbuf[0] == '-' ) {
        force_noquoting = true;
        buf1 = flagbuf.c_str() + 1;
      } else {
        force_noquoting = false;
        buf1 = flagbuf.c_str();
      }
      // parse buf1
      if ( m_flagstore && m_flagstore->hasFlag( buf1 ) == true ) {
        std::string replacementstr = m_flagstore->getFlagReplacement( buf1 );
        if ( ( quote == true ) && ( force_noquoting == false ) ) {
          char *newdstr = AGUIX_catTrustedAndUnTrusted( dstr.c_str(), replacementstr.c_str() );
          dstr = newdstr;
          _freesafe( newdstr );
        } else {
          dstr += replacementstr.c_str();
        }
      } else {
          m_replace_errors++;
      }
      mode = 0;
    }
  }
  return dstr;
}

FlagReplacer::FlagProducerMap::FlagProducerMap()
{
}

FlagReplacer::FlagProducerMap::~FlagProducerMap()
{
}

std::string FlagReplacer::FlagProducerMap::getFlagReplacement( const std::string &flag )
{
  if ( _flagvalue.count( flag ) > 0 ) {
    return _flagvalue[flag];
  }
  //TODO better throw an exception?
  return "";
}

bool FlagReplacer::FlagProducerMap::hasFlag( const std::string &flag )
{
  if ( _flagvalue.count( flag ) > 0 ) {
    return true;
  }
  return false;
}

void FlagReplacer::FlagProducerMap::registerFlag( const std::string &flag,
                                                  const std::string &value )
{
  _flagvalue[flag] = value;
}

FlagReplacer::FlagHelp::FlagHelp()
{
}

FlagReplacer::FlagHelp::~FlagHelp()
{
}

void FlagReplacer::FlagHelp::registerFlag( const std::string &flag,
                                           const std::string &description )
{
  _flagdescr[flag] = description;
}

std::list<std::string> FlagReplacer::FlagHelp::getListOfFlags() const
{
  std::map<std::string, std::string>::const_iterator it;
  std::list<std::string> flags;

  for ( it = _flagdescr.begin();
        it != _flagdescr.end();
        it++ ) {
    flags.push_back( (*it).first );
  }
  return flags;
}

std::string FlagReplacer::FlagHelp::getFlagDescription( const std::string &flag ) const
{
  std::map<std::string, std::string>::const_iterator it = _flagdescr.find( flag );
  if ( it != _flagdescr.end() ) {
    return (*it).second;
  }
  return "";
}

std::string FlagReplacer::requestFlag( const FlagHelp &flags )
{
  AGUIX *aguix = Worker::getAGUIX();
  AWindow *win;
  AGMessage *msg;
  int endmode=-1;
  std::string chosen_flag;
  int trow;
  
  win = new AWindow( aguix, 10, 10, 10, 10, catalog.getLocale( 338 ), AWindow::AWINDOW_DIALOG );
  win->create();

  AContainer *ac1 = win->setContainer( new AContainer( win, 1, 3 ), true );
  ac1->setMinSpace( 5 );
  ac1->setMaxSpace( 5 );

  win->addMultiLineText( catalog.getLocale( 578 ), *ac1, 0, 0, NULL, NULL );

  FieldListView *lv = (FieldListView*)ac1->add( new FieldListView( aguix,
                                                                   0, 0,
                                                                   100, 200,
                                                                   0 ),
                                                0, 1, AContainer::CO_MIN );
  lv->setHBarState(2);
  lv->setVBarState(2);

  lv->setNrOfFields( 3 );
  lv->setFieldWidth( 1, 5 );

  std::list<std::string> flaglist = flags.getListOfFlags();
  std::list<std::string>::iterator it;
  
  for ( it = flaglist.begin(); it != flaglist.end(); it++ ) {
    trow = lv->addRow();
    lv->setText( trow, 0, *it );
    lv->setText( trow, 2, flags.getFlagDescription( *it ) );
    lv->setPreColors( trow, FieldListView::PRECOLOR_ONLYACTIVE );
  }
  lv->maximizeX();
  ac1->readLimits();  
  
  AContainer *ac1_2 = ac1->add( new AContainer( win, 2, 1 ), 0, 2 );
  ac1_2->setMinSpace( 5 );
  ac1_2->setMaxSpace( -1 );
  ac1_2->setBorderWidth( 0 );
  Button *okb =(Button*)ac1_2->add( new Button( aguix,
                                                0,
                                                0,
                                                catalog.getLocale( 11 ),
                                                0 ), 0, 0, AContainer::CO_FIX );
  Button *cb = (Button*)ac1_2->add( new Button( aguix,
						0,
						0,
						catalog.getLocale( 8 ),
						0 ), 1, 0, AContainer::CO_FIX );
  win->setDoTabCycling( true );
  win->contMaximize( true );
  win->show();
  for ( ; endmode == -1; ) {
    msg = aguix->WaitMessage( win );
    if ( msg != NULL ) {
      switch ( msg->type ) {
        case AG_CLOSEWINDOW:
          if ( msg->closewindow.window == win->getWindow() ) endmode = 1;
          break;
        case AG_BUTTONCLICKED:
          if ( msg->button.button == okb ) endmode = 0;
          else if ( msg->button.button == cb ) endmode = 1;
          break;
      }
      aguix->ReplyMessage( msg );
    }
  }
  
  if ( endmode == 0 ) {
    // ok
    trow = lv->getActiveRow();
    if ( lv->isValidRow( trow ) == true ) {
      chosen_flag = lv->getText( trow, 0 );
    }
  }
  
  delete win;

  return chosen_flag;
}

int FlagReplacer::failed_flag_replacements()
{
    return m_replace_errors;
}

FlagReplacer::FlagProducerCallback::FlagProducerCallback( void *user_data )
    : m_user_data( user_data )
{
}

FlagReplacer::FlagProducerCallback::~FlagProducerCallback()
{
}

std::string FlagReplacer::FlagProducerCallback::getFlagReplacement( const std::string &flag )
{
    auto pos = flag.find( ':' );
    if ( pos != std::string::npos ) {
        std::string baseflag( flag, 0, pos );
        if ( m_flag_option_values.count( baseflag ) > 0 ) {
            std::string option( flag, pos );
            return m_flag_option_values[ baseflag ]( option, m_user_data );
        }
    }

    if ( m_flag_values.count( flag ) == 0 ) {
        return "";
    }

    return m_flag_values[ flag ]( m_user_data );
}

bool FlagReplacer::FlagProducerCallback::hasFlag( const std::string &flag )
{
    auto pos = flag.find( ':' );
    if ( pos != std::string::npos ) {
        std::string baseflag( flag, 0, pos );
        if ( m_flag_option_values.count( baseflag ) > 0 ) {
            return true;
        }
    }

    if ( m_flag_values.count( flag ) > 0 ) {
        return true;
    }
    return false;
}

void FlagReplacer::FlagProducerCallback::registerFlag( const std::string &flag,
                                                       std::function< std::string( void *user_data ) > callback )
{
    m_flag_values[ flag ] = callback;
}

void FlagReplacer::FlagProducerCallback::registerFlagWithOption( const std::string &flag,
                                                                 std::function< std::string ( const std::string &option, void *user_data ) > callback )
{
    m_flag_option_values[ flag ] = callback;
}
