// Copyright (C) 2024 Philipp Hofer
//
// Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
// the European Commission - subsequent versions of the EUPL (the "Licence").
// You may not use this work except in compliance with the Licence.
//
// You should have received a copy of the European Union Public License along
// with this program.  If not, you may obtain a copy of the Licence at:
// <https://joinup.ec.europa.eu/software/page/eupl>
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Licence is distributed on an "AS IS" basis,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the Licence for the specific language governing permissions and
// limitations under the Licence.

use log::{debug, info};
use serde::{Deserialize, Serialize};
use std::{
    cell::RefCell,
    fmt::{self, Display},
    rc::Rc,
    sync::Arc,
};

use crate::{config::Config, misc::Error, overview::parse};

pub mod responsible;

/// That's our struct, holding all the information of the law text.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Law {
    pub name: String,
    pub header: Vec<Heading>,
}

impl Law {
    pub fn from_config(path: &str) -> Result<Law, Error> {
        let (law_id, mut builder, parser) = Config::load(path)?;
        let pars = parse(law_id).unwrap();

        for par in pars {
            let cont = parser.parse(&par, &mut builder).unwrap();
            if !cont {
                break;
            }
        }

        Ok(builder.into())
    }

    //TODO: add test
    pub fn to_md(&self) {
        for header in &self.header {
            Self::print_md(header, 2);
        }
    }

    fn print_md(header: &Heading, level: usize) {
        println!("{} {}", "#".repeat(level), header);
        match &header.content {
            HeadingContent::Heading(h) => {
                for child in h {
                    Self::print_md(child, level + 1);
                }
            }
            HeadingContent::Paragraph(p) => {
                for par in p {
                    println!("{} {par}", "#".repeat(level + 1));
                }
            }
        }
    }
}

impl From<LawBuilder> for Law {
    fn from(builder: LawBuilder) -> Self {
        let mut ret = Vec::new();

        for header in builder.header {
            ret.push(Heading {
                name: header.borrow().name.clone(),
                desc: header.borrow().desc.clone(),
                content: header.borrow().clone().into(),
            });
        }

        Self {
            header: ret,
            name: builder.name,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Heading {
    pub name: String, //1. Hauptstück; 3. Theil; ...
    pub desc: Option<String>,
    pub content: HeadingContent, // 1. Theil; 1. Subtheil; ...
}

impl Display for Heading {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(desc) = &self.desc {
            f.write_str(&format!("{} ({desc})\n", self.name))
        } else {
            f.write_str(&format!("{}\n", self.name))
        }
    }
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum HeadingContent {
    Paragraph(Vec<Section>),
    Heading(Vec<Heading>),
}

impl From<ClassifierInstance> for HeadingContent {
    fn from(value: ClassifierInstance) -> Self {
        if value.sections.is_empty() {
            let mut ret = Vec::new();
            for child in value.children {
                ret.push(Heading {
                    name: child.borrow().name.clone(),
                    desc: child.borrow().desc.clone(),
                    content: child.borrow().clone().into(),
                });
            }

            Self::Heading(ret)
        } else {
            Self::Paragraph(value.sections)
        }
    }
}

/// Is used to generate a law struct. It's organized mainly by classifier.
#[derive(Debug)]
pub struct LawBuilder {
    name: String,

    /// Structure of the law text
    classifiers: Vec<Classifier>,

    /// Instances
    header: Vec<Rc<RefCell<ClassifierInstance>>>,

    last_instance: Option<Rc<RefCell<ClassifierInstance>>>,

    /// Stores the header of the next paragraph
    next_para_header: Option<String>,

    next_para_note: Option<String>,

    #[cfg(test)]
    pub history: Vec<String>,
}

impl PartialEq for LawBuilder {
    fn eq(&self, other: &Self) -> bool {
        self.classifiers == other.classifiers
            && self.header == other.header
            && self.next_para_header == other.next_para_header
    }
}

impl Default for LawBuilder {
    fn default() -> Self {
        Self::new("".into())
    }
}

impl LawBuilder {
    /// Creates a new law builder. Adds classifier for known law texts.
    pub fn new(name: String) -> Self {
        Self {
            name,
            classifiers: Vec::new(),
            header: Vec::new(),
            next_para_header: None,
            last_instance: None,
            next_para_note: None,
            #[cfg(test)]
            history: Vec::new(),
        }
    }

    pub fn add_classifier(&mut self, classifier: Classifier) {
        self.classifiers.push(classifier);
    }

    fn responsible_classifier(&self, name: &str) -> Option<&Classifier> {
        self.classifiers.iter().find(|&c| c.used_for(name))
    }

    fn find_parent(
        &self,
        cur: Option<Rc<RefCell<ClassifierInstance>>>,
        class: &Classifier,
    ) -> Option<Rc<RefCell<ClassifierInstance>>> {
        let mut cur = cur;
        while let Some(c) = cur {
            let (cur_name, cur_parent) = {
                let c_borrow = c.borrow();
                (c_borrow.name.clone(), c_borrow.parent.clone())
            };

            let cur_responsible_class = self.responsible_classifier(&cur_name).unwrap();
            if cur_responsible_class == class {
                return c.borrow_mut().get_parent();
            }

            cur = cur_parent;
        }
        None
    }

    /// Sets a new header.
    pub fn new_header(&mut self, name: &str) {
        let name = name.trim();
        #[cfg(test)]
        self.history.push(format!("New_header: {name}"));

        info!("new_header={name}");

        let responsible_class = self
            .responsible_classifier(name)
            .unwrap_or_else(|| panic!("No classifier for '{name}'"));

        let mut heading: ClassifierInstance = name.into();

        if let Some(last_instance) = &self.last_instance {
            let cur = Some(last_instance.clone());

            let parent = &self.find_parent(cur, responsible_class);
            match parent {
                None => {
                    if responsible_class.root {
                        let c = Rc::new(RefCell::new(heading));
                        self.header.push(c.clone());
                        self.last_instance = Some(c.clone());
                    } else {
                        heading.set_parent(last_instance.clone());
                        let c = Rc::new(RefCell::new(heading));
                        last_instance.borrow_mut().add_child(c.clone());
                        self.last_instance = Some(c.clone());
                    }
                }
                Some(parent) => {
                    heading.set_parent(parent.clone());
                    let c = Rc::new(RefCell::new(heading));
                    parent.borrow_mut().add_child(c.clone());
                    self.last_instance = Some(c.clone());
                }
            }
        } else {
            let c = Rc::new(RefCell::new(heading));
            self.header.push(c.clone());
            self.last_instance = Some(c.clone());
        }
    }

    /// Sets a new description for the last classifier.
    pub fn new_desc(&mut self, desc: &str) {
        let desc = desc.trim();
        #[cfg(test)]
        self.history.push(format!("New desc: {desc}"));

        debug!("new_desc={desc}");
        self.last_instance
            .clone()
            .unwrap()
            .borrow_mut()
            .set_desc(desc);
    }

    /// Adds a new paragraph.
    pub fn new_par(&mut self, par: String, content: Content) {
        #[cfg(test)]
        self.history.push(format!(
            "New_par: {par};{}",
            serde_json::to_string(&content).unwrap()
        ));

        debug!("new_par=par:{par};content:{content:#?}");

        let par_header = self.next_para_header.clone();
        self.next_para_header = None;

        let par_note = self.next_para_note.clone();
        self.next_para_note = None;

        self.last_instance
            .clone()
            .expect("Expect at least one classifier")
            .borrow_mut()
            .add_section(Section {
                symb: par,
                par_header,
                par_note,
                content,
            });
    }

    /// Next paragraph has a header, store its name.
    pub fn new_next_para_header(&mut self, header: &str) {
        #[cfg(test)]
        self.history.push(format!("New_new_para_header: {header}"));

        if let Some(next_para_header) = &self.next_para_header {
            self.new_header(&next_para_header.clone()); // promote to bigger header :-)
        }

        debug!("new_next_para_header={header}");
        self.next_para_header = Some(header.trim().into());
    }

    pub fn add_next_para_note(&mut self, content: String) {
        #[cfg(test)]
        self.history.push(format!("New_para_note: {content}"));

        self.next_para_note = Some(content);
    }
}

#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct Section {
    pub symb: String, // §"1", §"2", ...
    pub par_header: Option<String>,
    pub par_note: Option<String>,
    pub content: Content,
}

impl fmt::Debug for Section {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let par_header = self.par_header.as_deref().unwrap_or("");
        write!(f, "{} ({})\n{:#?}", self.symb, par_header, self.content)
    }
}

impl fmt::Display for Section {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut to_write = if let Some(header) = &self.par_header {
            format!("{} ({})\n{}", self.symb, header, self.content)
        } else {
            format!("{}\n{}", self.symb, self.content)
        };
        if let Some(note) = &self.par_note {
            to_write.push_str(&format!("\nBeachte: {}\n", note));
        }

        f.write_str(&to_write)
    }
}

#[derive(Clone, PartialEq)]
struct ClassifierInstance {
    name: String, //e.g. 1 Theilstück
    desc: Option<String>,
    sections: Vec<Section>,
    children: Vec<Rc<RefCell<ClassifierInstance>>>,
    parent: Option<Rc<RefCell<ClassifierInstance>>>,
}

impl ClassifierInstance {
    fn new(name: &str) -> Self {
        Self {
            name: name.into(),
            desc: None,
            parent: None,
            sections: Vec::new(),
            children: Vec::new(),
        }
    }

    fn set_parent(&mut self, parent: Rc<RefCell<ClassifierInstance>>) {
        self.parent = Some(parent);
    }

    fn get_parent(&self) -> Option<Rc<RefCell<ClassifierInstance>>> {
        self.parent.clone()
    }

    fn add_child(&mut self, child: Rc<RefCell<ClassifierInstance>>) {
        self.children.push(child);
    }

    fn set_desc(&mut self, desc: &str) {
        self.desc = Some(desc.into());
    }

    fn add_section(&mut self, section: Section) {
        self.sections.push(section);
    }
}

impl std::fmt::Debug for ClassifierInstance {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Classifier")
            .field("name", &self.name)
            .field("desc", &self.desc)
            .field("sections", &self.sections)
            .field("children", &self.children)
            .finish_non_exhaustive()
    }
}

impl From<&str> for ClassifierInstance {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

pub(crate) type ClassifierApplicable = Arc<dyn Fn(&str, &str) -> bool>;

#[derive(Clone)]
pub struct Classifier {
    pub name: String, // Hauptstück, Theil, Abschnitt, ol
    pub(crate) used_for_fn: ClassifierApplicable,
    instances: Vec<ClassifierInstance>,
    pub child: Vec<Rc<RefCell<Classifier>>>,
    pub root: bool,
}

impl PartialEq for Classifier {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl Classifier {
    pub fn new(name: &str, used_for_fn: ClassifierApplicable) -> Self {
        Self {
            name: name.into(),
            used_for_fn,
            child: Vec::new(),
            instances: Vec::new(),
            root: false,
        }
    }

    pub fn root(self) -> Self {
        Self { root: true, ..self }
    }

    fn used_for(&self, name: &str) -> bool {
        (self.used_for_fn)(&self.name, name)
    }
}

impl std::fmt::Debug for Classifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Classifier")
            .field("name", &self.name)
            .field("instances", &self.instances)
            .field("child", &self.child)
            .finish_non_exhaustive()
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Content {
    Text(String),       //This is my direct law text
    List(Vec<Content>), //(1) This is general law. (2) This is more specific law
    Multi(Vec<Content>),
}

impl Display for Content {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text(a) => f.write_str(&format!("{a}\n")),
            Self::List(a) | Self::Multi(a) => {
                let mut ret = String::new();
                for aa in a {
                    ret.push_str(&format!("{aa}"));
                }
                f.write_str(&ret)
            }
        }
    }
}

// Content::Item([
//      ContentPart::Multiple([
//          ContentPart::Text("(1) Behörden im Sinne...sind:")
//          ContentPart::List([
//              ContentPart::Text("1.")
//              ContentPart::Text("2.")
//          ])
//      ])
// ])
