package heufybot.modules;

import heufybot.utils.FileUtils;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Searcher
{
	private String rootLogPath;
	
	public Searcher(String rootLogPath)
	{
		this.rootLogPath = rootLogPath;
	}
	
	public String firstSeen(String source, String searchTerms)
	{
		File[] logsFolder = new File(rootLogPath).listFiles();
		Arrays.sort(logsFolder);

		for(File file : logsFolder)
		{
			int dateStart = file.getPath().lastIndexOf(File.separator) + 1;
			String date = "[" + file.getPath().substring(dateStart, dateStart + 10) + "] ";
			
			String[] lines = FileUtils.readFile(file.getPath()).split("\n");
			Pattern normalPattern = Pattern.compile(".*<(.?" + searchTerms + ")> .*", Pattern.CASE_INSENSITIVE);
			Pattern actionPattern = Pattern.compile(".*\\* (" + searchTerms + ") .*", Pattern.CASE_INSENSITIVE);
			
			for(String line : lines)
			{
				Matcher matcher = normalPattern.matcher(line);
				if(matcher.find())
				{
					return date + line;
				}
				else
				{
					matcher = actionPattern.matcher(line);
					if(matcher.find())
					{
						return date + line;
					}
				}
			}
		}
		return "No user matching \"" + searchTerms + "\" was found in the logs.";
	}
	
	public String lastSeen(String source, String searchTerms, boolean includeToday)
	{
		File[] logsFolder = new File(rootLogPath).listFiles();
		Arrays.sort(logsFolder);
		
		Date today = new Date();
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String todayString = formatter.format(today);
		
		for(File file : logsFolder)
		{
			int dateStart = file.getPath().lastIndexOf(File.separator) + 1;
			String date = "[" + file.getPath().substring(dateStart, dateStart + 10) + "] ";
			
			if(!(includeToday && date.equals(todayString)))
			{
				String[] lines = FileUtils.readFile(file.getPath()).split("\n");
				Pattern normalPattern = Pattern.compile(".*<(.?" + searchTerms + ")> .*", Pattern.CASE_INSENSITIVE);
				Pattern actionPattern = Pattern.compile(".*\\* (" + searchTerms + ") .*", Pattern.CASE_INSENSITIVE);
				
				for(String line : lines)
				{
					Matcher matcher = normalPattern.matcher(line);
					if(matcher.find())
					{
						return date + line;
					}
					else
					{
						matcher = actionPattern.matcher(line);
						if(matcher.find())
						{
							return date + line;
						}
					}
				}
			}
		}
		return "No user matching \"" + searchTerms + "\" was found in the logs.";
	}
}

@@ -1677,24 +1677,75 @@
 );%0A%09%09%0A%09%09for(
+int i = logsFolder.length - 1; i %3E= 1; i--)%0A%09%09%7B%0A%09%09%09
 File file : 
@@ -1734,33 +1734,33 @@
 %09%7B%0A%09%09%09File file 
-:
+=
  logsFolder)%0A%09%09%7B
@@ -1746,37 +1746,40 @@
 ile = logsFolder
-)%0A%09%09%7B
+%5Bi%5D;%0A%09%09%09
 %0A%09%09%09int dateStar

Fix LastSeen and LastSaw