
#include "gmenu.h"

#include "ggui-message-c.h"
#include "gcore/gcomm.h"
#include "gcore/gerror.h"
#include "gcore/glaunch.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#ifndef WIN32
#include <unistd.h>
#include <sys/time.h>
#else
#include "gsys/win32.h"
#endif

static char temporary_file[512];
static char temporary_name[256];

static FILE *fd;

/* Prepare a temporary file to create a detached X-Window process */
void CFC_API xgag_detach( CFC_FzString title, CFC_FzString name)
{
#ifndef WIN32
    struct timeval tp;
    struct timezone tzp;

    if (gettimeofday( &tp, &tzp) != 0)
        sic_perror( "gettimeofday");

    sprintf( temporary_file, "%s%s%ld.%ld", sic_s_get_logical_path( "GAG_TMP:"), "gag_tmp", tp.tv_sec, tp.tv_usec);
#else
    char temp_path[MAX_PATH];

    GetTempPath( MAX_PATH, temp_path);
    GetTempFileName( temp_path, "tmp", 0, temporary_file);
#endif
    sprintf( temporary_name, "%s", CFC_fz2c_string( name));
    fd = fopen( temporary_file, "w");
    if (fd == NULL) {
      ggui_c_message( seve_f, "DIALOGS", "Cannot create %s", temporary_file);
      sic_do_exit( 1);
    }
    fprintf( fd, "%s\n", CFC_fz2c_string( title));
    fprintf( fd, "%s\n", CFC_fz2c_string( name));
}

/* Start a command menu */
void CFC_API xgag_menu( CFC_FzString label)
{
    fprintf( fd, "%s\n", "MENU");
    fprintf( fd, "%s\n", CFC_fz2c_string( label));
}

/* End a command menu */
void CFC_API xgag_endmenu( )
{
    fprintf( fd, "%s\n", "ENDMENU");
}

/* Add a command in a menu */
void CFC_API xgag_command( CFC_FzString label, CFC_FzString command)
{
    fprintf( fd, "%s\n", CFC_fz2c_string( label));
    fprintf( fd, "%s\n", CFC_fz2c_string( command));
}

/* Add a command in a menu */
void CFC_API xgag_uri_menu( CFC_FzString label, CFC_FzString uri)
{
    fprintf( fd, "<URI>\n");
    fprintf( fd, "%s\n", CFC_fz2c_string( label));
    fprintf( fd, "%s\n", CFC_fz2c_string( uri));
}

/* Create the detached X-Window process */
void CFC_API xgag_launch( )
{
    fclose( fd);

    kill_menu(); /* destroy previous menu */
    launch_menu( temporary_file);
}

/**
 * Terminate (close) the input GUI-menu. The help file name associated
 * to the GUI-menu was used as its identifier.
 *
 * @param[in] name is the help file name (null terminated Fortran string).
 * @return nothing.
 */
void CFC_API xgag_end_detach( CFC_FzString name)
{
    kill_menu();
}

/**
 * Terminate (close) all the GUI-menus.
 *
 * @return nothing.
 */
void CFC_API xgag_end_detach_all()
{
    kill_menu();
}

char *xgag_get_detach_name()
{
    return temporary_name;
}
