package parser

import (
	
	
	
)

var temporaryParagraphKey = NewContextKey()

type setextHeadingParser struct {
	HeadingConfig
}

func ( []byte) (byte, bool) {
	 := 0
	 := len()
	 := util.TrimLeftLength(, []byte{' '})
	if  > 3 {
		return 0, false
	}
	 += 
	 := util.TrimLeftLength([:], []byte{'='})
	 := byte('=')
	var  int
	if  == 0 {
		 = util.TrimLeftLength([:], []byte{'-'})
		 = '-'
	}
	if util.IsSpace([-1]) {
		 -= util.TrimRightSpaceLength([:])
	}
	if !(( > 0 && + == ) || ( > 0 && + == )) {
		return 0, false
	}
	return , true
}
NewSetextHeadingParser return a new BlockParser that can parse Setext headings.
func ( ...HeadingOption) BlockParser {
	 := &setextHeadingParser{}
	for ,  := range  {
		.SetHeadingOption(&.HeadingConfig)
	}
	return 
}

func ( *setextHeadingParser) () []byte {
	return []byte{'-', '='}
}

func ( *setextHeadingParser) ( ast.Node,  text.Reader,  Context) (ast.Node, State) {
	 := .LastOpenedBlock().Node
	if  == nil {
		return nil, NoChildren
	}
	,  := .(*ast.Paragraph)
	if ! || .Parent() !=  {
		return nil, NoChildren
	}
	,  := .PeekLine()
	,  := matchesSetextHeadingBar()
	if ! {
		return nil, NoChildren
	}
	 := 1
	if  == '-' {
		 = 2
	}
	 := ast.NewHeading()
	.Lines().Append()
	.Set(temporaryParagraphKey, )
	return , NoChildren | RequireParagraph
}

func ( *setextHeadingParser) ( ast.Node,  text.Reader,  Context) State {
	return Close
}

func ( *setextHeadingParser) ( ast.Node,  text.Reader,  Context) {
	 := .(*ast.Heading)
	 := .Lines().At(0)
	.Lines().Clear()
	 := .Get(temporaryParagraphKey).(*ast.Paragraph)
	.Set(temporaryParagraphKey, nil)
	if .Lines().Len() == 0 {
		 := .NextSibling()
		 = .TrimLeftSpace(.Source())
		if  == nil || !ast.IsParagraph() {
			 := ast.NewParagraph()
			.Lines().Append()
			.Parent().InsertAfter(.Parent(), , )
		} else {
			.(ast.Node).Lines().Unshift()
		}
		.Parent().RemoveChild(.Parent(), )
	} else {
		.SetLines(.Lines())
		.SetBlankPreviousLines(.HasBlankPreviousLines())
		 := .Parent()
		if  != nil {
			.RemoveChild(, )
		}
	}

	if .Attribute {
		parseLastLineAttributes(, , )
	}

	if .AutoHeadingID {
		,  := .AttributeString("id")
		if ! {
			generateAutoHeadingID(, , )
		} else {
			.IDs().Put(.([]byte))
		}
	}
}

func ( *setextHeadingParser) () bool {
	return true
}

func ( *setextHeadingParser) () bool {
	return false