use crate::effects::star_field;
use crate::slide::Slide;
use crate::slide_show_config::Context;
use crate::utils::{draw_text_with_background, screen_center};
use macroquad::color::{BLACK, Color, ORANGE, VIOLET};
use macroquad::math::Vec2;
use macroquad::prelude::{
    BLUE, GREEN, RED, YELLOW, clear_background,
};
use macroquad::time::get_time;
use macroquad::window::{screen_height, screen_width};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct CreativeDemoCfg {
    pub title: String,
}

#[derive(Debug)]
pub struct CreativeDemo {
    cfg: CreativeDemoCfg,
    animation_state: usize,
    last_update: f64,
    first_display: bool,
}

impl CreativeDemo {
    pub fn new(cfg: CreativeDemoCfg) -> Box<Self> {
        Box::new(Self {
            cfg,
            animation_state: 0,
            last_update: 0.0,
            first_display: false,
        })
    }
}

impl Slide for CreativeDemo {
    fn display(&mut self, ctx: &Context<'_>) {
        if self.first_display {
            self.first_display = true;
            self.last_update = get_time();
        }
        clear_background(BLACK);
        star_field();

        let rainbow = [
            RED,
            ORANGE,
            YELLOW,
            GREEN,
            BLUE,
            Color::from_hex(0x4B0082),
            VIOLET,
        ];
        let mid_point = rainbow.len() / 2;

        for ndx in (0..=self.animation_state).rev() {
            if ndx == 0 {
                let bg_color = rainbow[mid_point].with_alpha(0.8);
                draw_text_with_background(
                    &self.cfg.title,
                    screen_center(),
                    &ctx.slide_show_theme.heading_config,
                    rainbow[mid_point],
                    bg_color,
                );
            } else {
                let offset = Vec2::new(screen_width(), -screen_height()) * 0.05 * ndx as f32;

                let ne_bg_color = rainbow[mid_point + ndx].with_alpha(0.8);
                draw_text_with_background(
                    &self.cfg.title,
                    screen_center() + offset,
                    &ctx.slide_show_theme.heading_config,
                    rainbow[mid_point - ndx],
                    ne_bg_color,
                );

                let sw_bg_color = rainbow[mid_point - ndx].with_alpha(0.8);
                draw_text_with_background(
                    &self.cfg.title,
                    screen_center() - offset,
                    &ctx.slide_show_theme.heading_config,
                    rainbow[mid_point + ndx],
                    sw_bg_color,
                );
            }
        }

        if get_time() - self.last_update > 0.5 {
            self.animation_state = (self.animation_state + 1) % (mid_point + 1);
            self.last_update = get_time();
        }
    }
}
