package id.co.gtc.erhacam;

import Database.PhotoReviewClass;
import Database.Sqlite;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.AnchorPane;
import org.tinylog.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ReviewView {

    @FXML
    private AnchorPane mainpane;

    @FXML
    private AnchorPane reviewpane;

    @FXML
    public void initialize(){
        Platform.runLater(()->{
            reviewpane.prefWidthProperty().bind(mainpane.widthProperty());
            int height = 120;
            double factor = 4.0/3.0;
            Sqlite sql = new Sqlite();
            PhotoReviewClass[] prcs = sql.GetAll();
            if (prcs!=null){
                ExecutorService executor = Executors.newSingleThreadExecutor();
                for(int ii=0;ii<prcs.length;ii++){
                    PhotoReviewClass prc = prcs[ii];
                    Thumbloader tl = new Thumbloader(prc,ii,height,factor);
                    tl.setOnSucceeded(e->{
                        AnchorPane row = tl.getValue();
                        if (row!=null) reviewpane.getChildren().add(row);
                    });
                    tl.setOnFailed(e-> Logger.error("Thumbloader for "+prc.getPrefix()+" failed, error: "+e.getSource().getException().getMessage()));
                    executor.submit(tl);
                }
                executor.shutdown();
            }
        });
    }

    // somehow this code is not working, it's not showing the thumbnails
    private static class Thumbloader extends Task<AnchorPane> {
        private final PhotoReviewClass prc;
        private final int height;
        private final double factor;
        private final int ii;
        public Thumbloader(PhotoReviewClass prc, int ii, int height, double factor){
            this.prc = prc;
            this.height = height;
            this.factor = factor;
            this.ii = ii;

        }
        @Override
        protected AnchorPane call()  {
            try{
                FXMLLoader loader = new FXMLLoader(getClass().getResource("PhotoRow.fxml"));
                AnchorPane row = loader.load();
                row.setPrefHeight(height);
                PhotoRow pr = loader.getController();
                AnchorPane.setTopAnchor(row, (1.0*ii*height)+5.0);
                pr.setDatetime(prc.getDateTime());
                pr.setPrefix(prc.getPrefix());
                pr.setPhotos((int)(factor*height), height, prc.thumbnails());
                return row;
            } catch (Exception e) {
                System.out.println("Error loading PhotoRow.fxml, error: "+e.getMessage());
                return null;
            }

        }
    }

    public void Unload(){
    }
}
