use std::default::Default;
use std::any::Any;
use std::path::Path;
use egui::{Ui, Widget, WidgetText};
use egui_commonmark::{CommonMarkCache, CommonMarkViewer};
use egui_tiles::TileId;
use crate::ui::Action;
use crate::ui::panels::TilePane;

pub struct Documentation {
    buffer: Option<String>,
    cache: CommonMarkCache,
}

impl TilePane for Documentation {
    fn title(&self) -> WidgetText {
        "Documentation".into()
    }

    fn ui(&mut self, ui: &mut Ui, _tile_id: TileId) -> Option<Action> {
        egui::ScrollArea::vertical()
            .id_salt("documentation")
            .max_width(1000.0)
            .show(ui, |ui| {
                if let Some(buffer) = &self.buffer {
                    CommonMarkViewer::new().show(ui, &mut self.cache, buffer);
                } else {
                    CommonMarkViewer::new().show(ui, &mut self.cache, "# No content loaded\nOpen a markdown file here!");
                }
            });

        None
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl Default for Documentation {
    fn default() -> Self {
        Self {
            buffer: None,
            cache: CommonMarkCache::default(),
        }
    }
}

impl Documentation {
    pub fn open(path: &Path) -> Self {
        Self {
            buffer: Some(std::fs::read_to_string(path).unwrap()),
            cache: CommonMarkCache::default(),
        }
    }

    pub fn get_mut(&mut self) -> &mut Option<String> {
        &mut self.buffer
    }
}