#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include "vg4.h"

#ifndef S_ISDIR
# define S_ISDIR(m)  (((m) & S_IFMT) == S_IFDIR)
#endif

int cmd_text(int, char **);

static int cmd_text_show(int, char **);


/* process command "text" */
int
cmd_text(int argc, char **argv)
{
  int retw = 0;

  if (argc < 2 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)  { goto help_text; }
  argc--; argv++;

  if (strcmp(argv[0], "show") == 0) {
    retw = cmd_text_show(argc, argv);
  } else {
    goto help_text;
  }

  return retw;

help_text:
  fprintf(stderr, "\nUsage: %s text <subcommand> [<options>]\n", argv0);
  fprintf(stderr, "Subcommands:\n");
  fprintf(stderr, "- show:    show text from file\n");
  fprintf(stderr, "(Use \"%s text <subcommand> -h|--help\" for more infos)\n", argv0);

  return 1;
} /* Ende cmd_text */


/* process command "text show" */
static int
cmd_text_show(int argc, char **argv)
{
  struct { int k_quit; int k_save; } kref;
  int i1, wsize;
  VG_BOOL wext;
  struct VG_Image *imgp;
  const char *textfile, *fontfile, *mlangdir, *fgcolor, *bgcolor, *maxwidth, *border, *hashcolor;
  char header[1024];
  size_t hpos;
  struct VG_Hash *hvar, *htags;

  if (argc < 2)  { goto help_text_show; }
  if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)  { goto help_text_show; }

  opterr = opterr ? opterr : 1;

  textfile = fontfile = mlangdir = fgcolor = bgcolor = maxwidth = border = hashcolor = NULL;
  wsize = VG_WINDOW_SIZE_LOW;
  wext = VG_FALSE;
  hvar = vg4->hash->create();

  while ((i1 = getopt(argc, argv, "+f:m:c:b:w:B:H:V:WE")) != -1) {
    switch(i1) {
      case 'f': fontfile = optarg; break;
      case 'm': mlangdir = optarg; break;
      case 'c': fgcolor = optarg; break;
      case 'b': bgcolor = optarg; break;
      case 'w': maxwidth = optarg; break;
      case 'B': border = optarg; break;
      case 'H': hashcolor = optarg; break;
      case 'V': { const char *kptr;
                  if ((kptr = strchr(optarg, '=')) != NULL) {
                    char vkey[128], vval[256];
                    vg4->misc->strscpy(vkey, sizeof(vkey), optarg, (size_t)(kptr - optarg));
                    vg4->misc->strcpy(vval, sizeof(vval), kptr + 1);
                    if (*vkey != '\0') { vg4->hash->setstr(hvar, vkey, vval); }
                  }
                }
                break;
      case 'W': wsize = VG_WINDOW_SIZE_HIGH; break;
      case 'E': wext = VG_TRUE; break;
      default:  goto help_text_show;
    }
  }

  if (optind < argc) { textfile = argv[optind++]; }
  if (textfile == NULL || *textfile == '\0') { goto help_text_show; }

  vg4->mlang->fb_locale("en");
  if (mlangdir != NULL && *mlangdir != '\0') {
    vg4->mlang->add(mlangdir);
  }

  /* set header */
  hpos = 0;
  header[hpos++] = '['; header[hpos] = '\0';
  if (fontfile != NULL && *fontfile != '\0') {
    snprintf(header + hpos, sizeof(header) - hpos, "%s=%s ", "font", fontfile);
    hpos = strlen(header);
  }
  if (fgcolor != NULL && *fgcolor != '\0') {
    snprintf(header + hpos, sizeof(header) - hpos, "%s=%s ", "fgcolor", fgcolor);
    hpos = strlen(header);
  }
  if (bgcolor != NULL && *bgcolor != '\0') {
    snprintf(header + hpos, sizeof(header) - hpos, "%s=%s ", "bgcolor", bgcolor);
    hpos = strlen(header);
  }
  if (maxwidth != NULL && *maxwidth != '\0') {
    snprintf(header + hpos, sizeof(header) - hpos, "%s=%s ", "maxwidth", maxwidth);
    hpos = strlen(header);
  }
  if (border != NULL && *border != '\0') {
    snprintf(header + hpos, sizeof(header) - hpos, "%s=%s ", "border", border);
    hpos = strlen(header);
  }
  header[hpos++] = ']'; header[hpos] = '\0';

  /* open window */
  vg4->window->size_extend(&wext);
  if (!vg4->window->open(wsize, VG_WINDOW_SCALE_BEST)) { return 1; }

  /* set keys */
  if ((kref.k_quit = vg4->input->key_insert("Quit", VG_FALSE, VG_FALSE)) == 0) { return 1; }
  vg4->input->key_setkbd(kref.k_quit, VG_INPUT_KBDCODE_Q);
  if ((kref.k_save = vg4->input->key_insert("Save", VG_FALSE, VG_FALSE)) == 0) { return 1; }
  vg4->input->key_setkbd(kref.k_save, VG_INPUT_KBDCODE_W);

  /* create image from text */
  imgp = vg4->font->loadtext(textfile, header, hvar, &htags);
  if (imgp == NULL) { return 1; }

  /* draw rectangle around tagged images */
  if (htags != NULL && hashcolor != NULL && *hashcolor != '\0') {
    void *vpos;
    const char *hkey;
    struct VG_Rect *prect;
    vpos = NULL;
    for (hkey = vg4->hash->list(htags, &vpos); vpos != NULL; hkey = vg4->hash->list(htags, &vpos)) {
      prect = vg4->hash->get(htags, hkey, NULL);
      if (prect != NULL) {
        vg4->image->draw_rect(imgp, prect, (int)strtol(hashcolor, NULL, 16), VG_FALSE);
        printf("Image-Tag \"%s\": %d+%d,%d+%d\n", hkey, prect->x, prect->w, prect->y, prect->h);
      }
    }
  }
  vg4->hash->destroy(htags);

  printf("Use key \"W\" to save text-image as text.bmp\n");
  printf("Use key \"Q\" to exit\n");
  fflush(stdout);

  /* show text-image */
  for (;;) {
    if (!vg4->input->update(VG_TRUE)) { break; }
    if (vg4->input->key_newpressed(kref.k_quit)) { break; }

    if (vg4->input->key_newpressed(kref.k_save)) {
      if (vg4->image->save(imgp, "text.bmp", VG_FALSE)) {
        printf("Image saved as text.bmp\n");
        fflush(stdout);
      }
    }

    vg4->window->clear();
    vg4->window->fill(VG_COLOR_RGB(64, 64, 64));
    vg4->window->copy(imgp, NULL, NULL);
    vg4->window->flush();
    vg4->misc->wait_time(50);
  }

  vg4->hash->destroy(hvar);
  vg4->image->destroy(imgp);

  vg4->input->key_remove(kref.k_quit);
  vg4->input->key_remove(kref.k_save);
  vg4->window->close();

  return 0;

help_text_show:
  fprintf(stderr, "\nUsage: %s text show [<options>] <text-file>\n", argv0);
  fprintf(stderr, "Show text from file\n");
  fprintf(stderr, "Options:\n");
  fprintf(stderr, " -f <string>: font (e.g. sys:low)\n");
  fprintf(stderr, " -m <string>: multilanguage directory\n");
  fprintf(stderr, " -c <string>: text color (0xRRGGBB)\n");
  fprintf(stderr, " -b <string>: background color (0xRRGGBB or \"transparent\")\n");
  fprintf(stderr, " -w <string>: greatest width of text-image (in pixels or percent)\n");
  fprintf(stderr, " -B <string>: border in pixels around text-image in background color\n");
  fprintf(stderr, " -H <string>: color (0xRRGGBB) for drawing a rectangle around tagged images\n");
  fprintf(stderr, " -V <string>: (repeated:) variable: <key>=<value>\n");
  fprintf(stderr, " -W:          use VG_WINDOW_SIZE_HIGH, (default: VG_WINDOW_SIZE_LOW)\n");
  fprintf(stderr, " -E:          use window-size extension\n");
  fprintf(stderr, "\n");
  fprintf(stderr, "Use key \"W\" to save text-image as text.bmp\n");
  fprintf(stderr, "Use key \"Q\" to exit\n");
  fprintf(stderr, "\n");
  return 1;
} /* Ende cmd_text_show */
