#include "libfspp.hpp"

#include "pic-library.hpp"

#include "renderer.hpp"
#include "config.hpp"

#include <vector>
#include <stack>
#include <list>
#include <string>

using std::vector;
using std::list;
using std::string;

void rdir_p(const string& argv)
{
  Config *conf = Config::get_instance();
  Render *render = Render::get_instance();

  std::stack<string> queued_dirs;

  std::cout << "starting thumbnailing" << std::endl;

  queued_dirs.push(argv);
  while (!queued_dirs.empty()) {
    string cur_dir = queued_dirs.top();
    queued_dirs.pop();
    for (file_iterator<file_t, default_order> i (cur_dir); i != i.end (); i.advance(false)) {

      string cur_file = i->getName();

      // exclude folders ?
      if (conf->p_excluded_picture_dirs().size() > 0) {
	list<string> excluded = conf->p_excluded_picture_dirs();
	bool stop = false;
	      
	for (list<string>::const_iterator epd = excluded.begin(), epd_end = excluded.end(); 
	     epd != epd_end; ++epd)
	  if (cur_file.substr(cur_file.rfind("/")+1) == *epd) {
	    stop = true;
	    break;
	  }
	      
	if (stop)
	  continue;
      }

      if (isDirectory(cur_file))
	queued_dirs.push(cur_file);
      else {
	if (!file_exists(render->image_get_fullpath(cur_file, 125, 96))) {
	  std::cout << "creating small thumbnail for image: " << cur_file  << std::endl;
	  render->create_scaled_image_wrapper(cur_file, 125, 96);
	}
	if (!file_exists(render->image_get_fullpath(cur_file, conf->p_v_res(), conf->p_h_res()))) {
	  std::cout << "creating fullscreen thumbnail for image: " << cur_file  << std::endl;
	  render->create_scaled_image_wrapper(cur_file, conf->p_v_res(), conf->p_h_res());
	}
      }
    }
  }
}

// stupid workaround
void Mms::clean_up()
{}

int main(int argc,char* argv[]) 
{
  Config *config = Config::get_instance();

  string homedir = getenv("HOME");

  struct stat file_stat;
  if (stat((homedir + "/.mms/").c_str(), &file_stat) == 0) {
    config->s_homedir(homedir + "/.mms/");
    config->s_var_data_dir(homedir + "/.mms/");
  } else {
    config->s_homedir("/etc/mms/");
    config->s_var_data_dir("/var/lib/mms/");
  }
  
  // now pass the configuration file using the correct path
  config->parse_configuration_file();

  std::cout << config->p_homedir() << ":" << config->p_temp_image_loc() << std::endl;

  if (argc <= 1) {

    std::cerr << "please specify at least one directory" << std::endl;
    return 1;

  } else if ((strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "--help") == 0)) {

    std::cout << "usage: ./mms-pic-library <directory> <directory> ..." << std::endl;
    return 0;

  }
  
  for (int i = 1; i < argc; ++i)
    rdir_p(argv[i]);
}

