use super::*;
#[derive(Debug, Clone)]
pub enum VideoMessage {
    EndOfStream,
    Open(url::Url),
    Pause,
    Play,
    Seek(f64),
    Stop,
    Test,
}

pub fn update(state: &mut State, message: VideoMessage) -> Task<Message> {
    match message {
        VideoMessage::EndOfStream => {
            state.video = None;
            Task::none()
        }
        VideoMessage::Open(url) => {
            match Video::new(&url)
                .inspect_err(|err| {
                    tracing::error!("Failed to play video at {}: {:?}", url, err);
                })
                .inspect(|video| {
                    tracing::error!("Framerate is {}", video.framerate());
                })
                .map(Arc::new)
            {
                Ok(video) => {
                    state.video = Some(video);
                    Task::none()
                }
                Err(err) => Task::done(Message::Error(format!(
                    "Error opening video at {}: {:?}",
                    url, err
                ))),
            }
        }
        VideoMessage::Pause => {
            if let Some(video) = state.video.as_mut().and_then(Arc::get_mut) {
                video.set_paused(true);
            }
            Task::none()
        }
        VideoMessage::Play => {
            if let Some(video) = state.video.as_mut().and_then(Arc::get_mut) {
                video.set_paused(false);
            }
            Task::none()
        }
        VideoMessage::Seek(position) => {
            // if let Some(ref video) = state.video {
            //     // video.seek(position, true);
            // }
            Task::none()
        }
        VideoMessage::Stop => {
            state.video = None;
            Task::none()
        }
        VideoMessage::Test => {
            let url = url::Url::parse(
                // "file:///home/servius/Projects/jello/crates/iced_video_player/.media/test.mp4",
                "https://gstreamer.freedesktop.org/data/media/sintel_trailer-480p.webm",
                // "https://www.youtube.com/watch?v=QbUUaXGA3C4",
            )
            .expect("Impossible: Failed to parse hardcoded URL");
            Task::done(Message::Video(VideoMessage::Open(url)))
        }
    }
}

pub fn player(video: &Video) -> Element<'_, Message> {
    container(
        VideoPlayer::new(video)
            .width(Length::Fill)
            .height(Length::Fill)
            .content_fit(iced::ContentFit::Contain)
            .on_end_of_stream(Message::Video(VideoMessage::EndOfStream)),
    )
    .style(|_| container::background(iced::Color::BLACK))
    .width(Length::Fill)
    .height(Length::Fill)
    .align_x(Alignment::Center)
    .align_y(Alignment::Center)
    .into()
}
