package logic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import data.Actor;
import data.DataBase;
import data.Director;
import data.Movie;
import data.User;
import data.comperators.MovieComparatorRating;

public class Recomendations {

	private DataBase db = DataBase.getInstance();
	private Movie bla;
	
	public ArrayList<Movie> withActor(Actor a , int limit){
		if(limit > 200)
			limit = 200;
		ArrayList<Movie> out = new ArrayList<>();
		for(Movie m : db.getMovies()) {
			System.out.println("comparing "+m.getTitle()+" and "+a.getName());
			if(m.getActors().contains(a)) {
				out.add(m);
//				if(out.size() >= limit)
//					Collections.sort(out, new MovieComparatorRating());
//					return out;
			}
		}
		Collections.sort(out, new MovieComparatorRating());
		return out;
	}
	
	public ArrayList<Movie> withDirector(Director d , int limit){
		if(limit > 200)
			limit = 200;
		ArrayList<Movie> out = new ArrayList<>();
		for(Movie m : db.getMovies()) {
			if(m.getDirectors().contains(d)) {
				out.add(m);
				if(out.size() >= limit)
					Collections.sort(out, new MovieComparatorRating());
					return out;
			}
		}
		Collections.sort(out, new MovieComparatorRating());
		return out;
	}
	
	public ArrayList<Movie> likedByUserWhoLike(Movie m ,int limit){
		if(limit > 200)
			limit = 200;
		HashMap<Movie,Integer> out = new HashMap<>();
		for(User u : db.getUsers()) {
			if(u.getRatings().containsKey(m.getId()) && u.getRatings().get(m.getId()) >= 5) {
				u.getRatings().forEach((k,v) -> {
					int users = 0;
					if(out.containsKey(db.getMovieById(k)))
						users = out.get(db.getMovieById(k));
					if(v >= 5)
					out.put(db.getMovieById(k),(users+1));
				});
			}
		}
		ArrayList<Movie> temp = new ArrayList<>();
		while(out.size() != 0) {
		out.forEach((k,v) -> {
			int max = 0;
			if(v > max) {
				max = v;
				bla = k;
			}
		});
		out.remove(bla);
		temp.add(bla);
		}
		Collections.sort(temp, new MovieComparatorRating());
		ArrayList<Movie> ret = new ArrayList<>();
		for(int i = 0;i < limit ;i++ ) {
			ret.add(temp.get(i));
		}
		return ret;
	}

	
	public ArrayList<Movie> withGenre(String genre, int limit){
		if(limit > 200)
			limit = 200;
		ArrayList<Movie> out = new ArrayList<>();
		for(Movie m : db.getMovies()) {
			if(m.getGenre().equals(genre)) {
				out.add(m);
				if(out.size() >= limit)
					Collections.sort(out, new MovieComparatorRating());
					return out;
			}
		}
		Collections.sort(out, new MovieComparatorRating());
		return out;
	}
}
