// 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 std::iter::Peekable;

use roxmltree::{Children, Node};

use crate::{law::Content, paragraph::parser::Expect};

use super::{Absatz, Tr};

#[derive(Debug, PartialEq)]
pub(crate) struct Table {
    trs: Vec<Tr>,
}
impl Table {
    // TODO: Combine mandatory check in parse + optional check in test -> Expect trait?
    pub(crate) fn test(n: &Node) -> bool {
        n.tag_name().name() == "table"
    }

    pub(crate) fn parse_full(n: &mut Peekable<Children>) -> Vec<Content> {
        Expect::from(n.peek().unwrap()).tag("table");

        let mut content = Vec::new();

        let mut trs = Vec::new();

        let c = n.next().unwrap();

        // Parse table
        for child in c.children() {
            trs.push(Tr::parse(&child));
        }
        content.push(Self::get_list(&trs));

        // erltext after table belongs to table
        while let Some(child) = n.peek() {
            if Absatz::test_with_typ(child, "erltext") {
                content.push(Content::Text(Absatz::parse(n.next().unwrap()).content));
            } else {
                break;
            }
        }

        content
    }

    pub(crate) fn get_list(trs: &Vec<Tr>) -> Content {
        let mut ret = Vec::new();

        for tr in trs {
            let mut txt = String::new();
            for td in &tr.tds {
                txt.push_str(&format!("{} ", td.absatz.content));
            }

            ret.push(Content::Text(format!("- {txt}",)));
        }

        Content::List(ret)
    }
}
