#include "main.h"

#include <fs++/file_iterator.h>
#include <fs++/file_t.h>

#include "imms.h"

#include "../config.hpp"

#include <iostream>

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

using filesystem::file_iterator ;
using filesystem::file_t ;
using filesystem::isDirectory ;

// convert string to lowercase
std::string lowercase(std::string s) {
  transform(s.begin(), s.end(), s.begin(), tolower);
  return s;
}

struct default_order : std::binary_function <const file_t&, const file_t&, bool>
{
  result_type operator() (first_argument_type a, second_argument_type b) const
  {
    return (lowercase(a.getName()) <= lowercase(b.getName()));
  }
};

std::string email = "default@imms.org";
int verbose = 1;

static Imms *imms = 0;

// check if the current file matches one of the types defined 
// in the configuration file pairs
MyPair check_type(const string& s, const list<MyPair>& temp)
{
  for (list<MyPair>::const_iterator iter = temp.begin(); iter != temp.end(); iter++)
    if (((s.length() - 1 - ((lowercase(s)).rfind("." + lowercase(iter->first))))) == (iter->first).size())
      return (*iter);
  return emptyMyPair;
}

// read a dir and spit out a list of files and dirs
void rdir_a(string argv)
{
  list<MyPair> filetypes;

  filetypes.push_back(MyPair("ogg", "ogg"));
  filetypes.push_back(MyPair("mp3", "mp3"));

  for (file_iterator<file_t, default_order> i (argv); i != i.end (); i.advance(true))
    {
      string filename = (*i).getName();

      const MyPair filetype = check_type(filename, filetypes);
      if (filetype != emptyMyPair) {
	InfoFetcher::SongData data(-1, filename);
	imms->fetch_song_info(data);
      }
    }
}

// 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();

  if (!imms)
    {
      imms = new Imms();
      imms->setup(false);
    }

  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-library <directory> <directory> ..." << std::endl;
    return 0;

  }

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

