use super::combinator::context_many_till;
use super::error::CustomError;
use super::error::MyError;
use super::error::Res;
use super::parser_context::ChainBehavior;
use super::parser_context::ContextElement;
use super::parser_context::ExitMatcherNode;
use super::text::symbol;
use super::text::text_element;
use super::token::Bold;
use super::token::TextElement;
use super::token::Token;
use super::util::in_section;
use super::Context;
use crate::parser::parser_with_context::parser_with_context;
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::combinator::map;
use nom::combinator::peek;
use nom::combinator::recognize;
use nom::sequence::tuple;

pub fn bold<'r, 's>(context: Context<'r, 's>, i: &'s str) -> Res<&'s str, Bold<'s>> {
    let bold_start = parser_with_context!(context_bold_start)(&context);
    let parser_context = context
        .with_additional_node(ContextElement::ExitMatcherNode(ExitMatcherNode {
            exit_matcher: ChainBehavior::AndParent(Some(&context_bold_end)),
        }))
        .with_additional_node(ContextElement::Context("bold"));
    let (remaining, captured) = recognize(tuple((bold_start, |i| {
        context_many_till(&parser_context, text_element, context_bold_end)(i)
    })))(i)?;
    let ret = Bold { source: captured };
    Ok((remaining, ret))
}

fn can_start_bold<'r, 's>(context: Context<'r, 's>) -> bool {
    _preceded_by_whitespace(context) && !in_section(context, "bold")
}

fn context_bold_start<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
    if can_start_bold(context) {
        recognize(bold_start)(input)
    } else {
        // TODO: Make this a specific error instead of just a generic MyError
        return Err(nom::Err::Error(CustomError::MyError(MyError(
            "Cannot start bold",
        ))));
    }
}

fn context_bold_end<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
    let (remaining, actual_match) = recognize(bold_end)(input)?;
    peek(alt((
        // Must have whitespace after the end asterisk or it must be the end of that section (as checked by the exit matcher)
        tag(" "),
        tag("\t"),
        tag("\n"),
        |i| context.check_exit_matcher(i),
    )))(remaining)?;

    Ok((remaining, actual_match))
}

fn bold_start(input: &str) -> Res<&str, TextElement> {
    map(symbol("*"), TextElement::Symbol)(input)
}

fn bold_end(input: &str) -> Res<&str, TextElement> {
    map(symbol("*"), TextElement::Symbol)(input)
}

fn _preceded_by_whitespace<'r, 's>(context: Context<'r, 's>) -> bool {
    let mut context_iterator = context.iter().enumerate();
    loop {
        if let Some((i, ctx)) = context_iterator.next() {
            match ctx.get_data() {
                ContextElement::ExitMatcherNode(_) => {}
                ContextElement::PreviousElementNode(previous_element_node) => {
                    match &previous_element_node.element {
                        Token::TextElement(text_element) => {
                            match text_element {
                                TextElement::Span(_) => return false,
                                TextElement::Space(_) => return true,
                                TextElement::LineBreak(_) => return true,
                                TextElement::Symbol(_) => return false,
                                TextElement::Bold(_) => return false,
                                TextElement::Link(_) => return false,
                            };
                        }
                        Token::Paragraph(_) => unreachable!(),
                    };
                }
                ContextElement::StartOfParagraph => {
                    return true;
                }
                ContextElement::Context(_) => {}
                ContextElement::ListItem(_) => {}
                ContextElement::DocumentRoot(_) => {
                    return true;
                }
            }
        } else {
            break;
        }
    }
    false
}