use gtk::prelude::*;
use gtk::{glib, Application, ApplicationWindow, Button, Image};
use std::cell::Cell;
use std::fs;
use std::rc::Rc;

extern crate anyhow;

const APP_ID: &str = "org.gtk_rs.GObjectMemoryManagement1";

fn main() -> glib::ExitCode {
    // Create a new application
    let app = Application::builder().application_id(APP_ID).build();

    // Connect to "activate" signal of `app`
    app.connect_activate(build_ui);

    // Run the application
    app.run()
}

fn get_pictures_in_folder(folder: String) -> anyhow::Result<Vec<String>> {
    let paths = fs::read_dir(&folder).expect("Could not read given folder");
    let mut myvec = Vec::new();
    let accepted_exts = ["jpg", "jpeg", "png"];

    //We only want files, and only jpg or png
    for p in paths {
        let entry = p?;
        let path = entry.path();
        let md = fs::metadata(&path)?;
        if md.is_file() {
            if let Some(extension) = path.extension() {
                if let Some(ext) = extension.to_str() {
                    if accepted_exts.contains(&ext.to_lowercase().as_str()) {
                        myvec.push(path.to_string_lossy().to_string());
                    }
                }
            }
        }
    }

    dbg!(myvec.clone());
    Ok(myvec)
}

fn build_ui(application: &Application) {
    // Create a vertical container
    let mut vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);

    // Create the "Increase" button
    let button_increase = Button::builder()
        .label("Next")
        .margin_top(12)
        .margin_bottom(12)
        .margin_start(12)
        .margin_end(12)
        .build();

    let button_decrease = Button::builder()
        .label("Prev")
        .margin_top(12)
        .margin_bottom(12)
        .margin_start(12)
        .margin_end(12)
        .build();

    // A list of pictures with a mutable index ref
    let pics = get_pictures_in_folder(".".to_string()).unwrap();
    let sp = Rc::new(pics.clone());
    let nbr: usize = 0;
    //Une copie pour papa, une copie pour maman... C'est chiant
    let curr_pic = Cell::new(nbr);
    let curr_pic2 = Cell::clone(&curr_pic);

    // Create the image
    let image = Image::from_file(pics[curr_pic.get()].clone());
    image.set_hexpand(true);
    image.set_vexpand(true);
    image.set_size_request(-1, -1);

    // Connect the buttons' clicked signal to update the image
    let image_clone = image.clone(); // Clone the image widget reference for the closure
    let shared_pics = Rc::clone(&sp);
    button_increase.connect_clicked(move |_| {
        let new_index = (curr_pic.get() + 1) % shared_pics.len(); // Ensure the index wraps around
        curr_pic.set(new_index); // Update the current picture index
        image_clone.set_from_file(Some(shared_pics[curr_pic.get()].clone())); // Update the image
        println!("{:?}", curr_pic.get());
    });

    let image_clone = image.clone();
    let shared_pics = Rc::clone(&sp);
    button_decrease.connect_clicked(move |_| {
        let new_index = (curr_pic2.get().checked_sub(1).unwrap_or(0)); // Ensure the index wraps around
        curr_pic2.set(new_index); // Update the current picture index
        image_clone.set_from_file(Some(shared_pics[curr_pic2.get()].clone())); // Update the image
        println!("{:?}", curr_pic2.get());
    });

    // Put the widgets in the container
    vbox.append(&button_increase);
    vbox.append(&button_decrease);
    vbox.append(&image);

    // Create a window
    let window = ApplicationWindow::builder()
        .application(application)
        .title("Image Viewer")
        .default_width(800)
        .default_height(600)
        .child(&vbox)
        .build();

    // Present the window
    window.present();
}
