// 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::{Absatz, Expect, Schlussteil, Ziffernliste},
};

#[derive(Debug)]
pub(crate) struct Liste {
    pub(crate) content: Vec<Content>,
}
impl Liste {
    pub(crate) fn test(n: &Node) -> bool {
        n.tag_name().name() == "liste"
    }

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

        let mut content = Vec::new();

        let mut c = n.next().unwrap().children().peekable();

        // Parse stuff inside <liste>
        while let Some(child) = c.peek() {
            if Ziffernliste::test(child) {
                let liste = Ziffernliste::parse(&mut c);
                content.push(liste.get_content());
            } else if Schlussteil::test(child) {
                // 162 Schifffahrtsgesetz show use that a 'schlussteil' can be at the start of a list
                content.push(Content::Text(Schlussteil::parse(c.next().unwrap()).content));
            } else {
                break;
            }
        }

        // Parse stuff after <liste>, which logically still is for the list
        while let Some(child) = n.peek() {
            if Absatz::test_with_typ(child, "satz") {
                content.push(Content::Text(Absatz::parse(n.next().unwrap()).content));
            } else {
                break;
            }
        }

        Self { content }
    }
}
