/*
 *  setoutdircommand.cpp
 *  Mothur
 *
 *  Created by westcott on 1/21/10.
 *  Copyright 2010 Schloss Lab. All rights reserved.
 *
 */

#include "setdircommand.h"

//**********************************************************************************************************************
vector<string> SetDirectoryCommand::setParameters(){	
	try {
		CommandParameter ptempdefault("mothurfiles", "String", "", "", "", "", "","",false,false); parameters.push_back(ptempdefault);
        CommandParameter ptools("tools", "String", "", "", "", "", "","",false,false); parameters.push_back(ptools);
        CommandParameter pdebug("debug", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pdebug);
        CommandParameter pseed("seed", "Number", "", "0", "", "", "","",false,false); parameters.push_back(pseed);
        CommandParameter pmodnames("modifynames", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(pmodnames);
		CommandParameter pinput("input", "String", "", "", "", "", "","",false,false,true); parameters.push_back(pinput);
		CommandParameter poutput("output", "String", "", "", "", "", "","",false,false,true); parameters.push_back(poutput);
        CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
		CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
        
        abort = false; calledHelp = false;
		
		vector<string> myArray;
		for (int i = 0; i < parameters.size(); i++) {	myArray.push_back(parameters[i].name);		}
		return myArray;
	}
	catch(exception& e) {
		m->errorOut(e, "SetDirectoryCommand", "setParameters");
		exit(1);
	}
}
//**********************************************************************************************************************
string SetDirectoryCommand::getHelpString(){	
	try {
		string helpString = "";
		helpString += "The set.dir command can be used to direct the output files generated by mothur to a specific place.\n";
		helpString += "The set.dir command can also be used to specify the directory where your input files are located, the directory must exist.\n";
		helpString += "The set.dir command can also be used to override or set the default location mothur will look for files if it is unable to find them, the directory must exist.\n";
        helpString += "The set.dir command can also be used to set the location of the directory containing mothur's external tools, i.e. vsearch, uchime, prefetch, fasterqdump, if other than mothur's executable location. You can set this to /usr/bin for example. \n";
        helpString += "The set.dir command can also be used to run mothur in debug mode.\n";
        helpString += "The set.dir command can also be used to seed random.\n";
        helpString += "The set.dir command can also be used to set the modifynames parameter. Default=t, meaning if your sequence names contain ':' change them to '_' to avoid issues while making trees.  modifynames=F will leave sequence names as they are.\n";
		helpString += "The set.dir command parameters are input, output, mothurfiles and debug and one is required.\n";
        helpString += "To run mothur in debug mode set debug=true. Default debug=false.\n";
        helpString += "To seed random set seed=yourRandomValue. By default mothur seeds random with the start time.\n";
		helpString += "To return the output to the same directory as the input files you may enter: output=clear.\n";
		helpString += "To return the input to the current working directory you may enter: input=clear.\n";
		helpString += "To set the output to the directory where mothur.exe is located you may enter: output=default.\n";
		helpString += "To set the input to the directory where mothur.exe is located you may enter: input=default.\n";
		helpString += "To return the mothurfiles location to the default you provided at compile time you may enter:  mothurfiles=clear.\n";
		helpString += "To set the mothurfiles to the directory where mothur.exe is located you may enter: mothurfiles=default.\n";
		helpString += "The set.dir command should be in the following format: set.dir(output=yourOutputDirectory, input=yourInputDirectory, mothurfiles=yourTempDefault).\n";
		helpString += "Example set.outdir(output=/Users/lab/desktop/outputs, input=/Users/lab/desktop/inputs).\n";
		return helpString;
	}
	catch(exception& e) {
		m->errorOut(e, "SetDirectoryCommand", "getHelpString");
		exit(1);
	}
}
//**********************************************************************************************************************

SetDirectoryCommand::SetDirectoryCommand(string option) : Command()  {
	try {
		if(option == "help") { help(); abort = true; calledHelp = true; }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;}
        else if(option == "category") {  abort = true; calledHelp = true;  }
		
		else {
			OptionParser parser(option, setParameters());
			map<string, string> parameters = parser.getParameters();
			
			ValidParameters validParameter;
			output = validParameter.validPath(parameters, "output");
			if (output == "not found") {  output = "";  } 
			
			input = validParameter.validPath(parameters, "input");
			if (input == "not found") {  input = "";  }
			
			mothurfiles = validParameter.validPath(parameters, "mothurfiles");
			if (mothurfiles == "not found") {  mothurfiles = "";  }
            
            toolsLocation = validParameter.validPath(parameters, "tools");
            if (toolsLocation == "not found") {  toolsLocation = "";  }
            
            bool debug = false;
            bool nodebug = false;
            debugorSeedOnly = false;
            string temp = validParameter.valid(parameters, "debug");
			if (temp == "not found") {  debug = false;  nodebug=true; }
            else {  debug = util.isTrue(temp); }
            m->setDebug(debug);
            
            bool nomod = false;
            temp = validParameter.valid(parameters, "modifynames");
			if (temp == "not found") {  modifyNames = true;  nomod=true; }
            else {  modifyNames = util.isTrue(temp); }
            m->setChangedSeqNames(modifyNames);
            
            bool seed = false;
            temp = validParameter.valid(parameters, "seed");
            if (temp == "not found") { random = 0; }
            else {
                if (util.isInteger(temp)) { util.mothurConvert(temp, random); seed = true; }
                else { m->mothurOut("[ERROR]: Seed must be an integer for the set.dir command.\n"); abort = true; }
            }
            
            if (debug) { m->mothurOut("Setting [DEBUG] flag.\n"); }
            if (seed)  {
                m->setRandomSeed(random);
                m->mothurOut("Setting random seed to " + toString(random) + ".\n\n");
            }
            
			if ((input == "") && (output == "") && (mothurfiles == "") && (toolsLocation == "")&& nodebug && nomod && !seed) {
				m->mothurOut("[ERROR]: You must provide either an input, output, mothurfiles, tools, debug or modifynames for the set.dir command.\n");  abort = true;
			}else if((input == "") && (output == "") && (mothurfiles == "") && (toolsLocation == "")) { debugorSeedOnly = true; }
		}
	}
	catch(exception& e) {
		m->errorOut(e, "SetDirectoryCommand", "SetDirectoryCommand");
		exit(1);
	}
}
//**********************************************************************************************************************

int SetDirectoryCommand::execute(){
	try {
		if (abort) { if (calledHelp) { return 0; }  return 2;	}
		
        if (debugorSeedOnly) {  }
        else {
            m->mothurOut("Mothur's directories:\n");
            
            //redirect output
            if ((output == "clear") || (output == "")) {  output = "";  current->setOutputDir(output);  }
            else if (output == "default") {
                string output = current->getProgramPath();
                
                m->mothurOut("outputDir=" + output + "\n");
                current->setOutputDir(output);
            }else {
                output = util.removeQuotes(output);
                if (util.mkDir(output)) {
                    m->mothurOut("outputDir=" + output + "\n");
                    current->setOutputDir(output);
                }
            }
            
            //redirect input
            if ((input == "clear") || (input == "")) {  input = "";  current->setInputDir(nullVector);  }
            else if (input == "default") {
                string input = current->getProgramPath();
                //input = exepath.substr(0, (exepath.find_last_of('m')));
                
                m->mothurOut("inputDir=" + input+ "\n");
                vector<string> temp; temp.push_back(input);
                current->setInputDir(temp);
            }else {
                input = util.removeQuotes(input);
                vector<string> inputPaths;
                vector<string> temp; util.splitAtChar(input, temp, ';');
                
                for (int i = 0; i < temp.size(); i++) {
                    string inputPath = util.removeQuotes(temp[i]);
                    //add / to name if needed
                    string lastChar = inputPath.substr(inputPath.length()-1);
                    if (lastChar != PATH_SEPARATOR) { inputPath += PATH_SEPARATOR; }
            
                    inputPath = util.getFullPathName(inputPath);
                    
                    if (util.dirCheckExists(inputPath)) { inputPaths.push_back(inputPath); }
                }
            
                if (inputPaths.size() != 0) {
                    m->mothurOut("inputdir=\n");
                    for (int i = 0; i < inputPaths.size(); i++) {
                        m->mothurOut("\t" + inputPaths[i] + "\n");
                    }
                    m->mothurOutEndLine();
                    current->setInputDir(inputPaths);
                }
            }
            
            //set default location of mothurs files
            if (mothurfiles == "clear") {
#ifdef MOTHUR_FILES
				string defaultPath = MOTHUR_FILES;
                vector<string> defaultPaths;
                vector<string> temp; util.splitAtChar(defaultPath, temp, ';');
                
                for (int i = 0; i < temp.size(); i++) {
                    string defaultPath = util.removeQuotes(temp[i]);
                    //add / to name if needed
                    string lastChar = defaultPath.substr(defaultPath.length()-1);
                    if (lastChar != PATH_SEPARATOR) { defaultPath += PATH_SEPARATOR; }
            
                    defaultPath = util.getFullPathName(defaultPath);
                    defaultPaths.push_back(defaultPath);
                }
                
                if (defaultPaths.size() != 0) {
                    m->mothurOut("mothurfiles=\n");
                    for (int i = 0; i < defaultPaths.size(); i++) {
                        m->mothurOut("\t" + defaultPaths[i] + "\n");
                    }
                    m->mothurOutEndLine();
                }

				current->setDefaultPath(defaultPaths);
#else
				m->mothurOut("No default directory defined at compile time.\n"); 
				current->setDefaultPath(nullVector);
#endif
            }else if (mothurfiles == "") {  //do nothing
            }else if (mothurfiles == "default") {
                string tempdefault = current->getProgramPath();
                
                m->mothurOut("mothurfiles=" + tempdefault+ "\n");
                vector<string> temp; temp.push_back(tempdefault);
                current->setDefaultPath(temp);
            }else {
                mothurfiles = util.removeQuotes(mothurfiles);
                vector<string> defaultPaths;
                vector<string> temp; util.splitAtChar(mothurfiles, temp, ';');
                
                for (int i = 0; i < temp.size(); i++) {
                    string defaultPath = util.removeQuotes(temp[i]);
                    //add / to name if needed
                    string lastChar = defaultPath.substr(defaultPath.length()-1);
                    if (lastChar != PATH_SEPARATOR) { defaultPath += PATH_SEPARATOR; }
            
                    defaultPath = util.getFullPathName(defaultPath);
                    
                    if (util.mkDir(defaultPath)) { defaultPaths.push_back(defaultPath); }
                }
            
                if (defaultPaths.size() != 0) {
                    m->mothurOut("mothurfiles=\n");
                    for (int i = 0; i < defaultPaths.size(); i++) {
                        m->mothurOut("\t" + defaultPaths[i] + "\n");
                    }
                    m->mothurOutEndLine();
                    current->setDefaultPath(defaultPaths);
                }
            }
            
            //set default
            if ((toolsLocation == "default") || (toolsLocation == "clear")){
#ifdef MOTHUR_TOOLS
                string toolsPath = MOTHUR_TOOLS;
                
                vector<string> toolsPaths;
                vector<string> temp; util.splitAtChar(toolsPath, temp, ';');
                
                for (int i = 0; i < temp.size(); i++) {
                    string defaultPath = util.removeQuotes(temp[i]);
                    //add / to name if needed
                    string lastChar = defaultPath.substr(defaultPath.length()-1);
                    if (lastChar != PATH_SEPARATOR) { defaultPath += PATH_SEPARATOR; }
            
                    defaultPath = util.getFullPathName(defaultPath);
                    toolsPaths.push_back(defaultPath);
                }
                
                if (toolsPaths.size() != 0) {
                    m->mothurOut("mothurtools=\n");
                    for (int i = 0; i < toolsPaths.size(); i++) {
                        m->mothurOut("\t" + toolsPaths[i] + "\n");
                    }
                    m->mothurOutEndLine();
                }

                current->setDefaultPath(toolsPaths);
#else
                string temp = current->getProgramPath();
                m->mothurOut("tools=" + temp+ "\n");
                vector<string> temps; temps.push_back(temp);
                current->setToolsPath(temps);
#endif
            }else if (toolsLocation == "") {  //do nothing
            }else {
                toolsLocation = util.removeQuotes(toolsLocation);
                vector<string> defaultPaths;
                vector<string> temp; util.splitAtChar(toolsLocation, temp, ';');
                
                for (int i = 0; i < temp.size(); i++) {
                    string defaultPath = util.removeQuotes(temp[i]);
                    //add / to name if needed
                    string lastChar = defaultPath.substr(defaultPath.length()-1);
                    if (lastChar != PATH_SEPARATOR) { defaultPath += PATH_SEPARATOR; }
            
                    defaultPath = util.getFullPathName(defaultPath);
                    
                    if (util.mkDir(defaultPath)) { defaultPaths.push_back(defaultPath); }
                }
            
                if (defaultPaths.size() != 0) {
                    m->mothurOut("mothurtools=\n");
                    for (int i = 0; i < defaultPaths.size(); i++) {
                        m->mothurOut("\t" + defaultPaths[i] + "\n");
                    }
                    m->mothurOutEndLine();
                    current->setToolsPath(defaultPaths);
                }
            }
        }
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "SetDirectoryCommand", "execute");
		exit(1);
	}
}
//**********************************************************************************************************************/
