/************************************************************
**
** Application: TranJPEG
**
** Title:       c.main
**
*************************************************************/

/*
*
* Copyright (c) 2015, Chris Johnson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the copyright holder nor the names of their
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/

/* Include files */
/* from standard clib */
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <locale.h>


#include "TaskLib:h.os"
#include "TaskLib:h.wimp"
#include "TaskLib:h.wimpt"
#include "TaskLib:h.werr"
#include "TaskLib:h.wos"
#include "TaskLib:h.err"
#include "TaskLib:h.mlo"
#include "TaskLib:h.bits"
#include "TaskLib:h.etc"
#include "TaskLib:h.mym"
#include "TaskLib:h.task"
#include "TaskLib:h.poll"
#include "TaskLib:h.scrap"
#include "TaskLib:h.temp"
#include "TaskLib:h.xhelp"
#include "TaskLib:h.fsx"
#include "TaskLib:h.constants"



/* headers from app */
#include "revision.h"

#include "h.reslink"
#include "h.xdeb"
#include "h.urllaunch"
#include "h.status"
#include "h.process"
#include "h.main"


#define WEB_BUTTON 8   /* web button icon ID in Info window */

/* paths for the help files */
#define HTML_HELP_FILE     "<TranJPEGRes$Dir>.Docs.help/html"
#define TEXT_HELP_FILE     "<TranJPEGRes$Dir>.Docs.help/txt"



static int     version = 135;
static char   *datestring = "(17 Sep 2018)";



void main_issuewarning (int tokennum)
{
  os_error   *warn;

  warn = geterror(tokennum);
  messagebox (warn->errmess);

  return;
}



static void tidy_on_exit (void)
{
  os_cli ("unset JT$In");
  os_cli ("unset JT$Out");
}



static void terminate (void)
{
  tidy_on_exit ();
  event (EVENT_ENDPROGRAM, NULL, 0);
  scrapfinit ();
  report (finittask ());
  exit (0);
}




static os_error *terminatemessage (wimp_msgstr * msg, int *ack)
{
  terminate ();
  return (NULL);

  USE (msg);
  USE (ack);
}



static os_error *uribouncemessage (wimp_msgstr * msg, int *ack)
{
  return (uri_bounce (msg));
  USE (ack);
}




/* deal with click on web button in info window */

static os_error *infoicon (int handle, int userhandle, wimp_mousestr * m)
{
  os_error   *err;

  err = NULL;

  switch (m->i)
  {
  case WEB_BUTTON:
    err = url_broadcast (WEB_URL);
    /* delete the menu unless the ADJUST button was used */
    if (m->bbits != 1) zapmenu ();
    break;
  }

  return (err);

  USE (handle);
  USE (userhandle);
}



static os_error *addmessages (void)
{
  os_error   *err;

  err = addmessage (terminatemessage, wimp_MCLOSEDOWN);
  if (!err) err = addmessage (uribouncemessage, wimp_MURI_RETURNRESULT);

  return (err);
}




/* open info window and pass back pointer */

static os_error *infodynamic (int *menu, int *handle)
{
  os_error   *err;
  static int  infowhandle;

  err = NULL;

  if (menu[0] == 0)
  {
    if (!infowhandle)
    {
      err = createwindow (TINFO, &infowhandle);
      if (!err)
      {
        addclickevent (infoicon, infowhandle, 0);
        addhelpevent(NULL,infowhandle,TINFO);
      }
    }
    writeicon (infowhandle, 1, wimpt_programname ());

#ifdef PROD
    writeiconf (infowhandle, 7, "%d.%02d %s", version / 100, version % 100,
		datestring);
#else
    writeiconf (infowhandle, 7, "Dev %s %s", REVISION, __DATE__);
#endif

    *handle = infowhandle;
  }

  return (err);
}

/* Following function tries to display the application help file.
 * Either html or text, in that order.
 * If neither is found - shows a warning message.
 * The original method using a !Help file in the application
 * directory which ran the html or text file, caused an
 * error if itself or the files were not found
 */

static os_error *show_help_file (void)
{
  os_error   *err;
  char       cmd[256];
  char      *file;
  int        type = 0;

  err = NULL;
  file = NULL;

  /* check that a browser has been seen by the filer */
  /* if so we can try to run the html help file */
  /* first check that it exists */
  fs_exists (HTML_HELP_FILE, &type);
  if ((os_read_var_size ("Alias$@RunType_FAF") != 0) && type)
  {
    file = HTML_HELP_FILE;
  }
  else
  {
    /* we can try to run the text help file instead */
    /* check that it exists */
    fs_exists (TEXT_HELP_FILE, &type);
    if (type)
    {
      file = TEXT_HELP_FILE;
    }
  }
  if (file)
  {
    /* run the file */
    sprintf(cmd,"Filer_Run %s",file);
    err = os_cli ( cmd ) ;
  }
  else
  {
    /* give user a warning message */
    main_issuewarning(WNOHELP);
  }
  return (err);
}




static os_error *opencontrol (void)
{
  os_error   *err;

  err = NULL;

  /* open up main action window */
  if (tw_processing)
  {
    err = status_open ();
  }
  else
  {
    status_close (0, 0);
    err = control_open ();
  }
  return (err);
}






static os_error *infodecode (int *menu)
{
  os_error   *err;

  err = NULL;


  switch (menu[0])
  {
  case 1:
    show_help_file ();
    break;

  case 2:
    err = opencontrol();
    break;

  case 3:
    terminate ();
    break;
  }

  return (err);
}




static os_error *iconbar (int handle, int userhandle, wimp_mousestr * m)
{
  os_error   *err;

  err = NULL;

  if (m->i == iconbaricon)
  {
    switch (m->bbits)
    {
      case 2:
        err = openupmenu (MINFO);
        break;

      case 4:
        err = opencontrol();
        break;

    }
  }

  return (err);

  USE (userhandle);
  USE (handle);
}




static os_error *setupmenus (void)
{
  os_error   *err;

  err = addclickevent (iconbar, -2, 0);

  setmenufns (MINFO, infodecode, infodynamic);
  setmenudynamic (MINFO, 0);
  setmenuflags (MINFO, MFINFO);

  return (err);
}







int main (void)
{
  os_error  *err;
  int        handle_already_running;

  setlocale (LC_ALL, "ISO8859-1");

  err = wos_tasknametohandle ("TranJPEG", &handle_already_running);
  if (handle_already_running)
  {
    /* there is a version already runing */
      exit (0);
  }


  /* Now we need to initialise with the wimp */

  err = inittask ("TranJPEG", "TranJPEG", "!TranJPEG",
		  "<TranJPEGRes$Dir>", NULL, NULL);
  if (err)
  {
    report (err);
    exit (0);
  }

#ifndef PROD
  debugenable (NULL);
#endif

#ifdef LOGGING_ON
  lstart();
#endif

  if (!err) err = seticonbar ("!TranJPEG");
  if (!err) err = resinit ("<TranJPEGRes$Dir>");
  if (!err) err = addmessages();

  if (!err) err = menulostart ("<TranJPEGRes$Dir>", "Menus");
  if (!err) err = setupmenus ();
//////  if (!err) err = scrapinit ("TranJPEG", "TranJPEG");

  if(!err) err = configinit();

  if(!err) err=addhelp ( "<TranJPEGRes$Dir>", "Help" );

  /* A drag to the iconbar icon */
  adddataload (-2, iconbaricon, control_loadfiles);
  adddataloadtype (-2, iconbaricon, control_loadfiletype);

  event (EVENT_RUNPROGRAM, NULL, 0);

  if (err)
  {
    report (err);
    terminate ();
  }

  runtask ();

}





