#include "grabpng.h"
#include "cexev.h"
#include "logo.txt.h"
#include "readme.txt.h"
#include <string>
#include <vector>
#include <fstream>
#include <stdlib.h>

#include "ui/ui.h"

#include "util.h"

bool fileExists(char *path)
{
  std::fstream f;
  f.open(path, std::ios::in);
  if( f.is_open() )
  {
    f.close();
    return true;
  }
  f.close();
  return false;
}

void showHelp()
{
  printf("%s%s\n",logo_txt,readme_txt);
}

int main(int argc, char** argv)
{
   try
  {
    
    
    std::vector<char *>file;
    int doAlph = 0;
    bool doGrab = false;
    int grabArgsAt = 0;
    
    // Launch gui if no command line args
    if (argc == 1)
    {
      printf("%s\n",logo_txt);
      GrabPngUI ui;
      return ui.show(argc, argv);
    }
    
    // Read command line parameters
    for (int i=1; i<argc; i++) 
    {
      if (std::string("-?") == argv[i]) // show help
      {
        showHelp();
        return 0;
      }
      if (std::string("-z") == argv[i]) // not supported
      {
        fprintf(stderr,"Option -z not supported.\n");
      }
      if (std::string("-alph") == argv[i]) // add alph
      {
        doAlph = 1;
      }
      if (std::string("-noalph") == argv[i]) // remove alph
      {
        doAlph = -1;
      }
      else if (i > 1 && std::string("-grab") == argv[i-2])  // grab
      {
        doGrab = true;
        grabArgsAt = i-1;
      }
      else if (fileExists(argv[i])) // file path
      {
        file.push_back(argv[i]);
      }
    }
    
    // check args
    
    // more args passed but no file found
    if (!file.size()) 
    {
      fprintf(stderr,"\n  <!>\n\n");
      GrabPngUI ui;
      return ui.show (1,argv); // launch gui (user fails it)
    }
    
    // file(s) found but no batch args
    if (!doAlph && !doGrab) 
    {
      GrabPngUI ui;
      return ui.show (argv, file[0]); // launch gui
    }
    
    // get ready to do the batch thing
    
    int grabX = 0;
    int grabY = 0;
    int width; int height;
    PngGrabber p;
    
    // loop through files
    for(unsigned i = 0; i < file.size(); i++)
    {
      if (!p.open(file[i])) continue;
      p.getSize(width,height);
      printf("\n%s [%ix%i]\n", file[i], width, height);
      if (doGrab) // set grab chunk
      {
        Evaluator e;
        e.width = width; e.height = height;
        grabX = atoi( e.eval(argv[grabArgsAt]) );
        grabY = atoi( e.eval(argv[grabArgsAt+1]) );
        p.grab(file[i], grabX, grabY);
        printf("Grabbing at (%d,%d).\n", grabX, grabY);
      }
      if (doAlph) // set alph chunk
      {
        if (doGrab) p.open(file[i]);  // re-open the file if modified by grab
        p.setAlph(file[i], doAlph);
        printf("%s alPh chunk.\n", (doAlph==1?"Adding":"Removing"));
      }
    } //done with files
    printf("\n");
  } //try
  catch (std::exception const& error)
  {
    fprintf(stderr,"\nERROR: %s\n",error.what());
    return 1;
  }
  
}
