/**
 * apiQuery for Project HomeFlix
 * sends a query to the omdb api
 */
package application;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;

import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;

import javafx.scene.image.Image;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;

public class apiQuery{
	
	public apiQuery(MainWindowController m, DBController db, Main main){
		mainWindowController=m;
		dbController=db;
		this.main = main;
	}
	
	private MainWindowController mainWindowController;
	private DBController dbController;
	private Main main;
	private Image im;
	private String[] responseString = new String[20];
	ArrayList<Text> responseText = new ArrayList<Text>();
	ArrayList<Text> nameText = new ArrayList<Text>();
	
	void startQuery(String titel, String streamUrl){
		URL url = null;
		Scanner sc = null;
		String apiurl = "https://www.omdbapi.com/?";	//API URL
		String moviename = null;
		String dataurl = null;
		String retdata = null;
		InputStream is = null;
		BufferedReader br = null;
		String fontFamily = main.getFONT_FAMILY();
		int fontSize = (int) Math.round(mainWindowController.size);
		
		responseText.removeAll(responseText);
		nameText.removeAll(nameText);

		try {

			//get film title
			sc = new Scanner(System.in);
			moviename = titel;

			// in case of no or "" Film title
			if (moviename == null || moviename.equals("")) {
				System.out.println("No movie found");
			}

			//remove unwanted blank
			moviename = moviename.trim();

			//replace blank with + for api-query
			moviename = moviename.replace(" ", "+");

			//URL wird zusammengestellt abfragetypen: http,json,xml (muss json sein um späteres trennen zu ermöglichen)
			dataurl = apiurl + "t=" + moviename + "&plot=full&r=json";

			url = new URL(dataurl);
			is = url.openStream();
			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

			// read data from response Stream
			while ((retdata = br.readLine()) != null) {
				//cut the json response into separate strings
				System.out.println(retdata);
				JsonObject object = Json.parse(retdata).asObject();
				
				responseString[0] = object.getString("Title", "");
				responseString[1] = object.getString("Year", "");
				responseString[2] = object.getString("Rated", "");
				responseString[3] = object.getString("Released", "");
				responseString[4] = object.getString("Runtime", "");
				responseString[5] = object.getString("Genre", "");
				responseString[6] = object.getString("Director", "");
				responseString[7] = object.getString("Writer", "");
				responseString[8] = object.getString("Actors", "");
				responseString[9] = object.getString("Plot", "");
				responseString[10] = object.getString("Language", "");
				responseString[11] = object.getString("Country", "");
				responseString[12] = object.getString("Awards", "");
				responseString[13] = object.getString("Metascore", "");
				responseString[14] = object.getString("imdbRating", "");
				responseString[15] = object.getString("Type", "");
				responseString[16] = object.getString("imdbVotes", "");
				responseString[17] = object.getString("imdbID", "");
				responseString[18] = object.getString("Poster", "");
				responseString[19] = object.getString("Response", "");
				
				//adding strings to the cache
				dbController.addCache(	streamUrl, responseString[0], responseString[1],responseString[2], responseString[3], responseString[4], responseString[5],
										responseString[6], responseString[7], responseString[8], responseString[9], responseString[10],responseString[11], responseString[12],
										responseString[13], responseString[14], responseString[15], responseString[16], responseString[17], responseString[18],
										responseString[19]);
				dbController.setCached(streamUrl);
				
				for(int i=0; i<20; i++){
					Text text = new Text(responseString[i]+"\n");
					responseText.add(text);
					responseText.get(i).setFont(Font.font(fontFamily, fontSize));
				}
				
				//if response == false then show mainWindowController.noFilmFound else create new Texts and add them to flowText
				if(responseString[19].equals("False")){
					mainWindowController.textFlow.getChildren().add(new Text(mainWindowController.noFilmFound));
					im = new Image("recources/icons/close_black_2048x2048.png");
					mainWindowController.image1.setImage(im);
				}else{
				//
					nameText.add(0, new Text(mainWindowController.title+": "));
					nameText.add(1, new Text(mainWindowController.year+": "));
					nameText.add(2, new Text(mainWindowController.rating+": "));
					nameText.add(3, new Text(mainWindowController.publishedOn+": "));
					nameText.add(4, new Text(mainWindowController.duration+": "));
					nameText.add(5, new Text(mainWindowController.genre+": "));
					nameText.add(6, new Text(mainWindowController.director+": "));
					nameText.add(7, new Text(mainWindowController.writer+": "));
					nameText.add(8, new Text(mainWindowController.actors+": "));
					nameText.add(9, new Text(mainWindowController.plot+": "));
					nameText.add(10, new Text(mainWindowController.language+": "));
					nameText.add(11, new Text(mainWindowController.country+": "));
					nameText.add(12, new Text(mainWindowController.awards+": "));
					nameText.add(13, new Text(mainWindowController.metascore+": "));
					nameText.add(14, new Text(mainWindowController.imdbRating+": "));
					nameText.add(15, new Text(mainWindowController.type+": "));


					for(int i=0; i<nameText.size(); i++){
						nameText.get(i).setFont(Font.font (fontFamily, FontWeight.BOLD, fontSize));	
					}
					
					mainWindowController.textFlow.getChildren().remove(0, mainWindowController.textFlow.getChildren().size());
					
					for(int i=0;i<nameText.size(); i++){
						mainWindowController.textFlow.getChildren().addAll(nameText.get(i),responseText.get(i));
					}
					
					//if there is no poster
					if(responseString[18].equals("N/A")){
						im = new Image("recources/icons/close_black_2048x2048.png");
					}else{
						im = new Image(responseString[18]);
					}
					mainWindowController.image1.setImage(im);
				}
			}

		} catch (Exception e) {
			mainWindowController.textFlow.getChildren().add(new Text(e.toString()));
			System.out.println(e);
		} finally {
			//closes datainputStream, InputStream,Scanner if not already done
			try {
				if (br != null) {
					br.close();
				}

				if (is != null) {
					is.close();
				}

				if (sc != null) {
					sc.close();
				}
			} catch (Exception e2) {
				;
			}
		}
	}
}
