import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.awt.*;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Production {
    private static final String basePosterPath = "./resources/Posters/";
    //--------------------------------------
    private int       ID        = -1;                 //Referencia a DB
    private File      mFile     = null;
    private Document  docu      = null;
    private DBManager DBman     = null;
    private ImageIcon poster    = null;
	//IMDB
    private String    IMDb_url      = "Empty";
    private String    IMDb_rating   = "Empty";
    private String    duration      = "Empty";
    private String    summary       = "Empty";
    private String    posterPath    = "noImage.jpg";
    private ArrayList<String> country   = null;
    private ArrayList<String> genres    = null;
    private ArrayList<String> actors    = null;
    private ArrayList<String> language  = null;
    //--------------------------------------
    public static String cleanString(String s) {
        int index = s.lastIndexOf(" (");
        if (index != -1)
            s = s.substring(0, index);
        index = s.lastIndexOf(",");
        if (index != -1)
            s = s.substring(0 , index);
        return s;
    }
    public static String getAttText(ArrayList<String> Att) {
        if(Att != null) {
            String base = "";
            for (String att : Att) {
                base = base+att+"   ";
            }
            return base;
        } else {
            return "No information.";
        }
    }
    private void savePoster() {
        String taux;
        File filePath;
        //---------
        taux = IMDb_url.substring(IMDb_url.indexOf("title/")+6);
        taux = taux.substring(0,taux.indexOf("/"))+".jpg";
        filePath = new File(basePosterPath+taux);
        try {
            BufferedImage buffer = (BufferedImage)poster.getImage();
            ImageIO.write(buffer,"jpg",filePath);
            posterPath = taux;
        } catch (Exception ex) {}
    }
    private void downloadPoster(String url) {
        BufferedImage buffer;
        try {
            URL urlPath = new URL(url);
            buffer = ImageIO.read(urlPath);
            poster = new ImageIcon(buffer);
            savePoster();
        } catch (Exception ex1) {
            try {
               File filePath = new File(basePosterPath+"noImage.jpg");
               buffer = ImageIO.read(filePath);
               poster = new ImageIcon(buffer);
            } catch (Exception ex2) {}
        }
    }
    private void posterResize(){
        Image img = poster.getImage();
        img = img.getScaledInstance(182,268,Image.SCALE_SMOOTH);
        poster = new ImageIcon(img);
    }
    //--------------------------------------
	protected Production(File mf, DBManager db) {
	    DBman   = db;
        mFile   = mf;
        docu    = null;
	}
    //--------------------------------------
	protected boolean setProduction(String url) {
		try {
            docu = Jsoup.connect(url).get();
			if (docu != null) {
			    int         indx;
			    Elements    auxa;
			    String      auxt;
                String[]    token;
			    country = new ArrayList<>();
                genres  = new ArrayList<>();
                actors  = new ArrayList<>();
                language= new ArrayList<>();
                //--------------------------
                IMDb_url    = docu.baseUri();
                //---------
                duration    = docu.select("#title-overview-widget .subtext time").text();
                //---------
                summary     = docu.select("#title-overview-widget .summary_text").text();
                //---------
                auxt = docu.select("#title-overview-widget .ratingValue").text();
                indx = auxt.lastIndexOf("/");
                if (indx != -1) IMDb_rating = auxt.substring(0, indx);
                //---------
				auxa = docu.select("#title-overview-widget .subtext [href*='genre']");
				for (Element gen : auxa){
					auxt = gen.text();
                    auxt = cleanString(auxt);
					genres.add(auxt);
				}
                //---------
                auxa = docu.select("#title-overview-widget .credit_summary_item [itemprop=actors]");
				for (Element act : auxa) {
                    auxt = act.text();
                    auxt = cleanString(auxt);
					actors.add(auxt);
				}
                //---------
                auxt = docu.select("#main_bottom .txt-block:contains(Country:)").text();
                auxt = auxt.replaceAll(" ","");
                auxt = auxt.substring(auxt.indexOf(":")+1);
                token = auxt.split("\\|");
                for(String coun : token) {
                    country.add(coun);
                }
                //---------
                auxt = docu.select("#main_bottom .txt-block:contains(Language:)").text();
                auxt = auxt.replaceAll(" ","");
                auxt = auxt.substring(auxt.indexOf(":")+1);
                token = auxt.split("\\|");
                for(String lang : token) {
                    language.add(lang);
                }
                //---------
                auxt = docu.select("#title-overview-widget .poster img[src]").toString();
				int index_op    = auxt.lastIndexOf("src=");
				int index_end   = auxt.lastIndexOf(" itemprop");
				if (index_op != -1 && index_end != -1)
                    auxt = auxt.substring(index_op+5,index_end-1);
				else auxt = null;
				downloadPoster(auxt);
				return true;
			} else return false;
		} catch (Exception ex) {
            return false;
		}
	}
    //--------------------------------------
    public int          getID(){
        return ID;
    }
    public File         getFile() {
        return mFile;
    }
    public Document     getDocu() {
        return docu;
    }
    public DBManager    getDBman() {
        return DBman;
    }
    public ImageIcon    getPoster() {
        return poster;
    }
    public String       getPosterPath() {
        return posterPath;
    }
    public String       getIMDb_url() {
        return IMDb_url;
    }
    public String       getIMDb_rating() {
        return IMDb_rating;
    }
    public String       getDuration() {
        return duration;
    }
    public String       getSummary() {
        return summary;
    }
    public ArrayList<String> getCountry() {
        return country;
    }
    public ArrayList<String> getActors() {
        return actors;
    }
    public ArrayList<String> getGenres() {
        return genres;
    }
    public ArrayList<String> getLanguage() {
        return language;
    }
    //--------------------------------------
    public void setID(int id){
        ID = id;
    }
    public void setPoster(String spos) {
        //Get the image...
        try {
            File filePath = new File(basePosterPath + spos);
            BufferedImage buffer = ImageIO.read(filePath);
            poster = new ImageIcon(buffer);
        } catch (Exception ex) {
            try {
                File filePath = new File(basePosterPath + "noImage.jpg");
                setPosterPath(basePosterPath + "noImage.jpg");
                BufferedImage buffer = ImageIO.read(filePath);
                poster = new ImageIcon(buffer);
            } catch (Exception ex2) {
            }
        }
        //Resize to the poster size
        posterResize();
    }
    public void setPosterPath(String path) {
        posterPath = path;
    }
    public void setIMDb_url(String url) {
        IMDb_url = url;
    }
    public void setIMDb_rating(String rat) {
        IMDb_rating = rat;
    }
    public void setDuration(String durat) {
        duration = durat;
    }
    public void setSummary(String sum) {
        summary = sum;
    }
    public void setCountry(ArrayList<String> coun) {
        country = coun;
    }
    public void setActors(ArrayList<String> act) {
        actors = act;
    }
    public void setGenres(ArrayList<String> gen) {
        genres = gen;
    }
    public void setLanguage(ArrayList<String> lan) {
        language = lan;
    }
    //--------------------------------------
    public String getGenreStr() {
        return getAttText(genres);
    }
    public String getCountryStr() {
        return getAttText(country);
    }
    public String getLanguageStr() {
        return getAttText(language);
    }
    public String getActorsStr() {
        return getAttText(actors);
    }
}