#include <iostream>
#include <string>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/regex.hpp>

#include "PhotoCompressArchiver.hh"

// Alias the namespace for readability
namespace bpo = boost::program_options;

void header()
{
    std::cout << BOLD << "Photo Compress Archiver -- " << version << "\n" << ENDC;
    std::cout << "  Copyright 2017-2018 -- David Sorber\n";
    std::cout << "  >>> Utilizing packJPG by Matthias Stirner\n" << std::endl;    
}

void usage(char** argv)
{
    // Remove leading "./" if it exits
    char* app_name = argv[0];
    if (argv[0][0] == '.' && argv[0][1] == '/')
    {
        char* app_name = &argv[0][2];
    }
    
    header();
    std::cout << "USAGE: " << app_name << " [-hdk] [-t <num threads>] "
              << "[-f <filter regex>] <file path>\n\n";
    std::cout << "Positional arguments:\n";
    std::cout << "  <file path>           path in which to recursively look "
              << "for input files\n\n";
    std::cout << "General options:\n";
    std::cout << "  -h [ --help ]         display this help message\n";
    std::cout << "  -d [ --decompress ]   find '*.pjg' files and decompress them\n";
    std::cout << "  -k [ --delete-orig ]  delete original files\n";
    std::cout << "  -t [ --num-threads ]  number of processing threads to use (max 2x system cores)\n";
    std::cout << "  -f [ --filter ]       regex with which to filter out input files\n";    
    std::cout << std::endl;
}

// NOTE: useful filter: -f ^\\._.+$
int main(int argc, char** argv)
{
    uint32_t num_cores = std::thread::hardware_concurrency();
    uint32_t num_threads = 0;
    std::string search_path("");
    std::string filter_str("");
    bpo::variables_map general_opts_vm;
    
    try
    {
        // General options
        bpo::options_description general_opts("General options");
        general_opts.add_options()
            ("help,h", "display this help message")
            
            ("decompress,d", "find '*.pjg' files and decompress them")
            
            ("delete-orig,k", "delete orignal files")
            
            ("num-threads,t", 
             bpo::value<uint32_t>(&num_threads)->default_value(num_cores), 
             "number of processing threads to use")
             
            ("filter,f", 
             bpo::value<std::string>(&filter_str), 
             "regex with which to filter out input files")
             
             // Note this has to be here even though it's a positional argument
            ("file_path", bpo::value<std::string>(&search_path)->required(),
             "path in which to recursively look for input files")            
        ;

        // Positional arguments
        bpo::positional_options_description pos_opts; 
        pos_opts.add("file_path", 1);
        
        // Parse general/positional options
        bpo::store(bpo::command_line_parser(argc, argv)
                   .options(general_opts)
                   .positional(pos_opts).run(), 
                   general_opts_vm);
        
        // Display help if the option is listed or if no arguments are provided
        if (general_opts_vm.count("help") || (argc == 1)) 
        {
            usage(argv);
            return 0;
        }
        
        bpo::notify(general_opts_vm);
    }
    catch (std::exception& e) 
    {
        std::cerr << BOLD << RED << "\nERROR: " << ENDC << e.what() << "\n"
                  << std::endl;
        return -1;
    }
    
    // Make sure that path specified actually exists before proceeding
    if (! bfs::exists(search_path))
    {
        std::cerr << BOLD << RED << "\nERROR: " << ENDC << "the path \"" 
                  << search_path << "\" does not exist\n" << std::endl;
        return -2;
    }
    
    // Validate number of threads
    if (num_threads > (2 * std::thread::hardware_concurrency()))
    {
        std::cerr << BOLD << RED << "\nERROR: " << ENDC << "the maximum number "
                  << "of threads is: " << (2 * num_cores) << "(2 * " << num_cores 
                 << ")\n" << std::endl;
        return -2;
    }
    
    // Check for, and if present validate the filter regex
    boost::regex filter_regex("");
    if (general_opts_vm.count("filter"))
    {
        try
        {
            filter_regex = filter_str;
        }
        catch (std::exception& e) 
        {
            std::cerr << BOLD << RED << "ERROR: " << ENDC << "the filter \"" 
                      << filter_str << "\" is not a valid regular expression.\n";
            std::cerr << "       " << e.what() << std::endl;
            return -1;
        }
    }
    
    // Display header and options
    header();
    std::cout << "  [" << num_cores << " cores detected]\n" << std::endl;
    std::cout << BOLD << ">>> Options:" << ENDC << std::endl;
    
    // Decode/store decompress option
    bool decompress = false;
    if (general_opts_vm.count("decompress"))
    {
        decompress = true;        
    }
    std::cout << "  decompress mode        => " << (decompress ? "ON" : "OFF") 
              << std::endl;
    
    // Decode/store delete-orig option
    bool delete_orig = false;
    if (general_opts_vm.count("delete-orig"))
    {
        delete_orig = true;        
    }
    std::cout << "  delete original files  => " << (delete_orig ? "ON" : "OFF") 
              << std::endl;
              
    // Number of processing threads option
    std::cout << "  num processing threads => " << num_threads << std::endl;
    
    // Filter regex option
    if (general_opts_vm.count("filter"))
    {
        std::cout << "  filter regex           => ON (" << filter_str << ")\n";
    }
    std::cout << std::endl;
    
    // Create the PCA object and let 'er rip!
    auto pca = new PhotoCompressArchiver(search_path, num_threads, decompress, 
                                         delete_orig, filter_regex);
    pca->execute();
    delete pca;
    
    return 0;
}
