package main;

import java.util.ArrayList;
import java.util.Iterator;

import data.DataBase;
import data.DataParser;
import data.Movie;
import logic.Recomendations;

public class Main {

	Recomendations rec = new Recomendations();
	
	public static void main(String[] args) {
		new Main().start(args);
	}
	
	public void start(String[] args) {
		new DataParser();
		int limit = 200;
		ArrayList<Movie> printlist = new ArrayList<>();
		ArrayList<Movie> buffer;
		if(args.length != 0) {
			for(String s : args) {
				switch(s.substring(0,s.indexOf("="))) {
				case "--test":
					buffer = new ArrayList<>();
					for(Movie m : rec.withActor(DataBase.getInstance().getActorByName(s.substring(s.indexOf("=")+1).replaceAll("'", "")), 20)) {
						buffer.add(m);
					}
						printlist.addAll(combine(buffer,printlist));
					break;
				case "--genre":
					buffer = new ArrayList<>();
					for(Movie m : rec.withGenre(s.substring(s.indexOf("=")+1).replaceAll("'", ""), 20)) {
						buffer.add(m);
					}
						printlist = combine(buffer,printlist);
					break;
				case "--actor":
					buffer = new ArrayList<>();
					//DataBase.getInstance().printMovies();
					for(Movie m : rec.withActor(DataBase.getInstance().getActorByName(s.substring(s.indexOf("=")+1).replaceAll("'", "")), 20)) {
						buffer.add(m);
					}
						printlist.addAll(combine(buffer,printlist));
					break;
				case "--director":
					buffer = new ArrayList<>();
					for(Movie m : rec.withDirector((DataBase.getInstance().getDirectorByName(s.substring(s.indexOf("=")+1).replaceAll("'", ""))), 20)) {
						buffer.add(m);
					}
						printlist = combine(buffer,printlist);
					break;
				case "--film":
					buffer = new ArrayList<>();
					for(Movie m : rec.likedByUserWhoLike(DataBase.getInstance().getMovieByName(s.substring(s.indexOf("=")+1).replaceAll("'", "").trim()), 20)) {
						buffer.add(m);
					}
						printlist = combine(buffer,printlist);
					break;
				case "--limit":
					limit = Integer.parseInt(s.substring(s.indexOf("=")+1).replaceAll("'", ""));
					break;
				case "--printdb":
					System.out.println("printing db");
					//new DataParser();
					
					DataBase.getInstance().printMovies();
					break;
				default:
					System.out.println("argument "+s+" is unkown");
				}
			}
			if(printlist.size() > limit) {
				for (int i = 0; i < printlist.size()-limit; i++) {
					printlist.remove(i+limit);
				}
			}
			for(Movie m : printlist) {
				System.out.println(m);
			}
		}else {
			new ConsoleReader();
		}
	}
	
	private ArrayList<Movie> combine(ArrayList<Movie> a, ArrayList<Movie> b){
		ArrayList out = new ArrayList<>();
		if(b.isEmpty())
			return a;
		for(Movie m : a) {
			if(b.contains(a))
				out.add(m);
		}
		return out;
	}
	
	private void printList(ArrayList<Object> list) {
		for(Object o : list) {
			System.out.println(o);
		}
	}
	
}
