package parser

import (
	
	
	
)

type codeBlockParser struct {
}

// CodeBlockParser is a BlockParser implementation that parses indented code blocks.
var defaultCodeBlockParser = &codeBlockParser{}

// NewCodeBlockParser returns a new BlockParser that
// parses code blocks.
func () BlockParser {
	return defaultCodeBlockParser
}

func ( *codeBlockParser) () []byte {
	return nil
}

func ( *codeBlockParser) ( ast.Node,  text.Reader,  Context) (ast.Node, State) {
	,  := .PeekLine()
	,  := util.IndentPositionPadding(, .LineOffset(), .Padding, 4)
	if  < 0 || util.IsBlank() {
		return nil, NoChildren
	}
	 := ast.NewCodeBlock()
	 = text.NewSegmentPadding(.Start+, .Stop, )
	// if code block line starts with a tab, keep a tab as it is.
	if .Padding != 0 {
		preserveLeadingTabInCodeBlock(&, , 0)
	}
	.ForceNewline = true
	.Lines().Append()
	.AdvanceToEOL()
	return , NoChildren

}

func ( *codeBlockParser) ( ast.Node,  text.Reader,  Context) State {
	,  := .PeekLine()
	,  := util.IndentPositionPadding(, .LineOffset(), .Padding, 4)

	if util.IsBlank() &&  < 0 {
		 = text.NewSegment(.Stop-1, .Stop)
	} else if  < 0 {
		return Close
	} else {
		 = text.NewSegmentPadding(.Start+, .Stop, )
		.ForceNewline = true
		// if code block line starts with a tab, keep a tab as it is.
		if .Padding != 0 {
			preserveLeadingTabInCodeBlock(&, , 0)
		}
	}
	.Lines().Append()
	.AdvanceToEOL()
	return Continue | NoChildren
}

func ( *codeBlockParser) ( ast.Node,  text.Reader,  Context) {
	// trim trailing blank lines
	 := .Lines()
	 := .Len() - 1
	 := .Source()
	for  >= 0 {
		 := .At()
		if util.IsBlank(.Value()) {
			--
		} else {
			break
		}
	}
	.SetSliced(0, +1)
}

func ( *codeBlockParser) () bool {
	return false
}

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

func preserveLeadingTabInCodeBlock( *text.Segment,  text.Reader,  int) {
	 := .LineOffset() + 
	,  := .Position()
	.SetPosition(, text.NewSegment(.Start-1, .Stop))
	if  == .LineOffset() {
		.Padding = 0
		.Start--
	}
	.SetPosition(, )
}