use crate::tile;
use glib::Object;
use gtk::{prelude::*, subclass::prelude::*};
use std::{cell::RefCell, rc::Rc};

pub struct PaletteEntryPrivate {
    terrain: Rc<RefCell<tile::Terrain>>,
}

#[glib::object_subclass]
impl ObjectSubclass for PaletteEntryPrivate {
    const NAME: &'static str = "PaletteEntry";
    type Type = PaletteEntry;
    type ParentType = gtk::ListBoxRow;

    fn new() -> Self {
        Self {
            terrain: Rc::new(RefCell::new(tile::Terrain::Empty)),
        }
    }
}

impl ObjectImpl for PaletteEntryPrivate {}
impl WidgetImpl for PaletteEntryPrivate {}
impl ListBoxRowImpl for PaletteEntryPrivate {
    fn activate(&self) {
        println!("row activated: {:?}", self.terrain);
    }
}

glib::wrapper! {
    pub struct PaletteEntry(ObjectSubclass<PaletteEntryPrivate>) @extends gtk::ListBoxRow, gtk::Widget;
}

impl PaletteEntry {
    pub fn new(tile: &tile::Tile) -> Self {
        let row: Self = Object::builder().build();
        *row.imp().terrain.borrow_mut() = tile.terrain.clone();
        let layout = gtk::Box::builder().spacing(8).build();

        let image = gtk::Image::from_pixbuf(Some(&tile.image));
        image.set_width_request(100);
        image.set_height_request(88);

        layout.append(&image);
        layout.append(&gtk::Label::new(Some(&String::from(&tile.terrain))));

        row.set_child(Some(&layout));

        row
    }
}
