/* addurl.c
 *
 * WebGet: Acorn Web Fetcher and rewriter
 * Code to deal with add url dialogue
 *
 *  Joseph Heenan, 1998
 * All rights reserved.
 *
 * This source is not for release
 *
 * $Log: addurl,v $
 * Revision 1.13  1999/08/21 16:32:00  joseph
 * Allow numbers in the fetch filenames
 *
 * Revision 1.12  1998/08/30 18:31:48  joseph
 * Fetching of inline images may be specified more precisely
 *
 * Revision 1.11  1998/08/30 15:23:34  joseph
 * Clicking 'Add' when no url entered now raised an error and doesn't close
 * the window.
 *
 * Revision 1.10  1998/08/23 14:27:12  joseph
 * Added ability to drag URL/URI's to the iconbar.
 *
 * Revision 1.9  1998/08/12 21:41:09  joseph
 * Moved searchfordesc from addurl to fetchfile and made global
 *
 * Revision 1.8  1998/08/10 19:58:02  joseph
 * Defaults for include/exclude now put into addurl dialogue
 *
 * Revision 1.7  1998/08/10 19:19:52  joseph
 * Changed include-files to include, ditto for exclude.
 *
 * Revision 1.6  1998/08/09 15:41:08  joseph
 * Fixed bug with empty descriptions, and with corrected range of chars
 * used for filename.
 *
 * Revision 1.5  1998/08/09 15:06:59  joseph
 * Added include/exclude lists for URLs
 *
 * Revision 1.4  1998/07/25 17:36:59  joseph
 * Enabled Esc/Return in addurl window
 *
 * Revision 1.3  1998/07/25 17:12:29  joseph
 * Changed so adding a new fetch file causes menu to be rebuild if not fetching
 *
 * Revision 1.2  1998/07/25 16:45:29  joseph
 * Changes to support Acorn URI's broadcast method.
 *
 * Revision 1.1  1998/07/24 17:11:03  joseph
 * Added UI for adding URLs to a fetchfile
 *
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "swis.h"
#include "wimplib.h"
#include "wimpclib.h"

#include "defines.h"

#include "debug.h"
#include "url.h"
#include "config.h"
#include "IconNames.h"
#include "fetchfile.h"
#include "webget.h"

#include "addurl.h"

static int addurl_winhan = -1;


void addurl_opendesc( const char *url, const char *desc )
{
  char depth[64];
  wimpc_seticontext( addurl_winhan, ADDURL_URL, url );
  wimpc_seticontext( addurl_winhan, ADDURL_DESC, desc );

  sprintf( depth, "%d", config_linkdepth );
  wimpc_seticontext( addurl_winhan, ADDURL_LINKDEPTH, depth );
  wimpc_seticontext( addurl_winhan, ADDURL_INCLUDE, config_includefiles );
  wimpc_seticontext( addurl_winhan, ADDURL_EXCLUDE, config_excludefiles );

  wimpc_iconselect( addurl_winhan, ADDURL_FOLLOWALL,  config_links==links_all  );
  wimpc_iconselect( addurl_winhan, ADDURL_FOLLOWHOST, config_links==links_host );
  wimpc_iconselect( addurl_winhan, ADDURL_FOLLOWDIR,  config_links==links_dir  );

  wimpc_iconselect( addurl_winhan, ADDURL_IMAGESALL,  config_inlineimages==links_all  );
  wimpc_iconselect( addurl_winhan, ADDURL_IMAGESHOST, config_inlineimages==links_host );
  wimpc_iconselect( addurl_winhan, ADDURL_IMAGESDIR,  config_inlineimages==links_dir  );
  wimpc_iconselect( addurl_winhan, ADDURL_IMAGESNONE,  config_inlineimages==links_none  );

  wimpc_iconselect( addurl_winhan, ADDURL_FRAMES, config_inlineframes );

  wimpc_openwindowcentre( addurl_winhan, 0 );
  wimp_set_caret_position( addurl_winhan, ADDURL_URL, 0, 0, -1, strlen(url) );
}


void addurl_init( int winhan )
{
  addurl_winhan = winhan;
}

int addurl_open( const char *url, int checkonly )
{
  if ( url && url_handled( url ) != 0 ) return 0;

  if ( checkonly ) return 1; /* can handle URL */

  debug_printf(("recv'ed url : %s\n", url ));

  if ( url )
    addurl_opendesc( url, "Queued URLs" );
  else
    addurl_opendesc( "", "" );

  return 1; /* handle url */
}


static void addurl_addurl( const char *url, const char *desc, conf_followlinks links, int depth,
                           conf_followlinks images, int frames, const char *includefiles, const char *excludefiles )
{
  int newfile = 0;
  char fname[ 64 ];
  FILE *f = NULL;
  debug_printf(( "url = %s, desc = %s, links = %d, depth = %d, images = %d, frames = %d\n",
                 url, desc, links, depth, images, frames ));

  if ( fetchfile_searchfordesc( desc, fname, sizeof fname ) < 0 )
  {
    char fullfname[10 + sizeof(WEBGET_FETCHDIR".") ] = WEBGET_FETCHDIR".";
    char *fname = fullfname + sizeof(WEBGET_FETCHDIR".") - 1; /* 10 + null */
    char *end = fullfname + sizeof(fullfname) - 1;
    char *ptr = fname;
    const char *in = desc;
    int objtype;
    newfile = 1;
    debug_printf(("Desc not found - need to create new file\n"));
    if ( !*in )
      in = url;
    /* make up filename */
    while ( *in && ptr < end )
    {
      if (isalnum(*in))
        *ptr++ = *in;
      in++;
    }
    *ptr = 0;
    debug_printf(("Filename generated from Desc is '%s','%s'\n",fname,fullfname));
    while ( _swix( OS_File, _INR(0,1) | _OUT(0), 17, fullfname, &objtype ), objtype != 0 )
    {
      /* that file exists... try increasing last char till we find one that doesn't */
      char *x = fname + strlen(fname) - 1; /* point to last char */
      while ( tolower(*x) == 'z' && x > fname ) x--;
      if ( tolower( *x ) == 'z' )
      {
        E_REPORT( "Could not find a free fetch file - URL could not be added" );
        return;
      }
      (*x)++; /* inc. last non-z char */
    }

    /* create new fetch file */
    f = fopen( fullfname, "w" );
    /* write desc to new file */
    if ( f )
    {
      fetchfile_writehead( f );
      fprintf( f, "name=%s\n", desc );
    }
  }
  else
  {
    /* open existing fetch file for append */
    f = fopen( fname, "a" );
    debug_printf(("Desc found in %s\n", fname ));
  }

  if ( !f )
  {
    E_REPORT( "Could not write to fetch file - URL could not be added" );
    return;
  }

  /* add config followed by url */
  if ( fprintf( f, "linkdepth=%d\n"
                   "links=%s\n"
                   "inline-images=%s\n"
                   "frames=%s\n"
                   "include=%s\n"
                   "exclude=%s\n"
                   "url=%s\n",
                   depth,
                   links==links_all ? "all" : links==links_host ? "host" : "dir",
                   images==links_all ? "all" : images==links_host ? "host" : images==links_none ? "none" : "dir",
                   frames ? "yes" : "no",
                   includefiles,
                   excludefiles,
                   url ) < 0 )
  {
    E_REPORT( "Error writing to fetch file, URL could not be added" );
  }

  /* close fetch file */
  fclose( f );
  if ( newfile )
    frontend_recreatefetchmenu();
}


static int addurl_process( int window )
{
  conf_followlinks links = links_dir, images = links_dir;
  char *depth = wimpc_geticontext( window, ADDURL_LINKDEPTH );
  char *desc = wimpc_geticontext( window, ADDURL_DESC );
  char *url = wimpc_geticontext( window, ADDURL_URL );

  if ( !*url )
  {
    E_REPORT("You must enter a URL!");
    return 0;
  }

  if ( !*desc )
  {
    char *x = strstr( url, "://" );
    if ( x )
      desc = x + 3;
    else
      desc = url;
  }

  if ( !depth ) depth = "0";

  if ( wimpc_iconselected( window, ADDURL_FOLLOWALL ) )
    links = links_all;
  else if ( wimpc_iconselected( window, ADDURL_FOLLOWHOST ) )
    links = links_host;

  if ( wimpc_iconselected( window, ADDURL_IMAGESALL ) )
    images = links_all;
  else if ( wimpc_iconselected( window, ADDURL_IMAGESHOST ) )
    images = links_host;
  else if ( wimpc_iconselected( window, ADDURL_IMAGESNONE ) )
    images = links_none;

  addurl_addurl( url, desc, links, atoi(depth), images, wimpc_iconselected( window, ADDURL_FRAMES ),
    wimpc_geticontext( window, ADDURL_INCLUDE ), wimpc_geticontext( window, ADDURL_EXCLUDE ) );
  return 1;
}


int addurl_keypress( int key )
{
  switch ( key )
  {
    case 13:
      addurl_process( addurl_winhan );
      break;

    case 27:
      break;

    default:
      return 0; /* not handled */
  }

  wimp_close_window( &addurl_winhan );
  return 1; /* handled */
}


void addurl_mouseclick( int window, int icon, int but )
{
  if ( window != addurl_winhan ) return;

  if ( but & Wimp_MouseButtonMenu ) return;

  switch ( icon )
  {
    case ADDURL_FOLLOWALL:
    case ADDURL_FOLLOWHOST:
    case ADDURL_FOLLOWDIR:
    case ADDURL_IMAGESALL:
    case ADDURL_IMAGESHOST:
    case ADDURL_IMAGESDIR:
    case ADDURL_IMAGESNONE:
      wimpc_iconselect( window, icon, 1 ); /* affirm selected state of radios. adjust, grr. */
      break;

    case ADDURL_LINKDEPTH_DOWN:
    case ADDURL_LINKDEPTH_UP:
    {
      char depth[64];
      char *cur = wimpc_geticontext( window, ADDURL_LINKDEPTH );
//      debug_printf(( "cur = %p", cur ));
      if ( cur )
      {
        sprintf( depth, "%d", atoi(cur) + ( icon==ADDURL_LINKDEPTH_UP ? 1 : -1 ) );
        /* set caret position */
        wimpc_seticontext( window, ADDURL_LINKDEPTH, depth );
      }
      break;
    }

    case ADDURL_ADDURL:
      if ( !addurl_process( window ) )
        break; /* don't close window if error occured */
      /* fall through & close window */
    case ADDURL_CANCEL:
      wimp_close_window( &window );
      break;
  }
}
