use sfml::window::{Key, Event};
use sfml::graphics::{CircleShape, Color, Drawable, RectangleShape, RenderStates, RenderTarget, RenderWindow, Shape, Transformable, Font};
use crate::button::Button;
use sfml::system::Vector2f;

pub struct Slider<'a> {
    value: f32,
    left_button: Button<'a>,
    right_button: Button<'a>,
    slider_button: Button<'a>,
    rail: RectangleShape<'a>,
    root_position: Vector2f,
}

impl<'a> Slider<'a> {

    pub fn new(position: Vector2f, value: Option<f32>, font: &'a Font) -> Self {

        let val = match value {
            Some(v) => v,
            None => 0.0,
        };

        let left_button_position = position + Vector2f::new(0.0,0.0);
        let right_button_position = position + Vector2f::new(150.0,0.0);
        let slider_position = position + Vector2f::new(val,0.0);

        let mut slider = Slider {
            value: val,
            left_button: Button::new(Vector2f::new(30.0, 50.0), left_button_position, font),
            right_button: Button::new(Vector2f::new(30.0, 50.0), right_button_position, font),
            slider_button: Button::new(Vector2f::new(30.0, 50.0), slider_position, font),
            rail: RectangleShape::with_size(Vector2f::new(150.0, 2.0)),
            root_position: position,
        };

        slider.left_button.set_text("<");
        slider.right_button.set_text(">");

        slider.rail.set_position(position);

        slider
    }

    pub fn click(&mut self, click: Vector2f) {
        if Button::is_within(click, &self.left_button) {
            self.value -= 1.0;
        }
        if Button::is_within(click, &self.right_button) {
            self.value += 1.0;
        }
    }

    pub fn update(&mut self) {
        self.slider_button.set_position(self.root_position + Vector2f::new(self.value,0.0));
    }
}

impl<'s> Drawable for Slider<'s> {
    fn draw<'a: 'shader, 'texture, 'shader, 'shader_texture>(
        &'a self,
        render_target: &mut RenderTarget,
        _: RenderStates<'texture, 'shader, 'shader_texture>,
    ) {
        render_target.draw(&self.left_button);
        render_target.draw(&self.right_button);
        render_target.draw(&self.slider_button);
        render_target.draw(&self.rail);
    }
}