### A Nbdev script file ###
### Autogenerated file. Don't modify. ###

module Documenter
#export
using Base.Docs

#export
using TOML

#export
using Markdown

#export
using Distributed

#export
using ProgressMeter

#export
include("../src/Export.jl")

#export
include("../src/CodeRunner.jl")

#export
import Pluto: Notebook, Cell, load_notebook_nobackup

#export
begin
"""
> struct Section--> This is like the section of a page and is made up of one or multiple lines.
> * Fields:
>   * line--> String which makes up a section
"""
Base.@kwdef mutable struct Section
	line::String=""
end

"""
> Section(line)--> Helper function to call the constructor of the type Section
"""
Section(line)=Section(line=line)
"""
> line(section::Section)--> Getter for accessing the underlying field line.
"""
line(section::Section)=section.line
end

#export
begin
"""
> Page--> The type that represents a page in a document.
> * Fields:
>   * sections--> Array of Section type.
>   * name--> Name of the module being documented.
"""
struct Page
	sections::Array{Section,1}
    name::AbstractString
end

"""
> Page--> Helper function to create constructer for Page type.
"""
Page(sections, path)=Page(sections=sections, path=path)
	
"""
> sections--> Getter for accessing the underlying field sections of Page.
"""
sections(p::Page)=p.sections
	
"""
> name--> Getter for accessing the underlying field name of Page.
"""
name(p::Page)=p.name
end

#export
"""
> runandupdatenb(fn::AbstractString)--> Run the notebook in the supplied path and update the notebook with the output of each cell.
"""
function runandupdatenb(fn::AbstractString)
	nb=load_notebook_nobackup(fn)
	return CodeRunner.executecode(nb)
end

#export
begin
"""
> struct Functiondocs--> Stores the document of different objects.
> * funcdocs--> Array of strings.
"""
mutable struct Functiondocs
	funcdocs::Array{String, 1}
end

"""
> Functiondocs(funcdocs)--> Helper for accessing the FunctionDocs constructer.
"""
Functiondocs(funcdocs)=Functiondocs(funcdocs) 
end

#export
begin
        		

"""
> stitchcode(cell::Cell)--> Stitches the code in a Pluto notebook cell with the output of that code. The output is a code block.
"""
function stitchcode(cell::AbstractArray)
	op=' '
	if length(cell) > 1
	    op=values(cell[2])
	end
	string("```","\n$(cell[1])\n","------\nOutput\n------\n","$(op)\n", "```\n")
end
	
"""
> stitchcode(cellop::AbstractString)--> Removes the quotes from a string and creates a code block with that string inside the newely formed code block
"""
function stitchcode(cellop::AbstractString)
	cleanedop=Export.strip(Export.strip(cellop,"\""), "\"")
	string("```","\n$cleanedop\n","```\n")
end
	
"""
> stitchcode(fdocs::Functiondocs)--> When supplied with a FunctionDocs type, stitchCode appends together the object docstrings and generates documentation for that particular object
"""
function stitchcode(fdocs::Functiondocs)
		funcdocs=""
		
		for fdoc in fdocs.funcdocs
		    funcdocs=string(funcdocs, "$(fdoc)\n\n")
	    end
		
		funcdocs
end
end

#export
"""
> collectfuncdocs(obj)--> Collects objects (functions, methods, macro structs etc.) and creates an array of documents (generated from the docstrings). Creates aFunctionDocs type from these documents.
"""
function collectfuncdocs(obj)
	docs=doc(obj)
	searchurl = "https://github-link.vercel.app/api?ghUrl="
	giturl = getsettings(joinpath("..", "Project.toml"), ["settings", "github_url"])

	pattern = r"\\(.+\\)*(.+)(\.jl)"
	fn = uppercasefirst(Export.strip(basename(join(match(pattern, string(first(methods(obj)))).captures)), r"[0-9_]"))
	
	searchurl = "$searchurl$giturl/blob/master/src/$fn&q=$(string(nameof(obj)))"
    fdocs=["$(docs.meta[:results][i].object) [source]($searchurl)" for i=1:length(docs.meta[:results])]
	Functiondocs(fdocs)
end

#export
begin
	
"""
> showdoc(o)--> Takes an object and builds markdown documentation.
"""
function showdoc(o)
	docs=collectfuncdocs(o)
	stitchcode(docs)
end
end

#export
begin
function maintainheading(str:: AbstractString)
	res= nothing
	if startswith(str, """<div class="markdown"><h2>""")
			res = Export.strip(Export.strip(Export.strip(str, """<div class="markdown"><h2>"""), """</h2>"""), """</div>""")
			res = string("## ", res)
	else
		res = str
	end
	res
end

"""
> CreatePage--> Creates the Page type from the markdown and example code cells of the supplied notebook. The filename is the name of the notebook which is parsed.
"""
function createpage(fn::AbstractString, nb::Notebook)
	sections=Section[]
	res=nothing
	
	for cell in nb.cells
		
		if cell.errored
			error("Build stopped. Seems like the code $cell.code has an error")
			break
	    end
	    if startswith(cell.code, "md")
			cleanop = maintainheading(cell.output.body)
			push!(sections, Section(cleanop))
		elseif !startswith(cell.code, "#export") && !startswith(cell.code, "#hide") 
			if occursin( "showdoc", cell.code)
				cleanedop=Export.strip(cell.output.body, "\"")
				cleanedop=replace(cleanedop, "\\n"=>"\n")
				push!(sections, Section(cleanedop))
			elseif occursin( "#noop", cell.code)
				stitchedcode=stitchcode([cell.code])
			    push!(sections, Section(stitchedcode))
			else
				stitchedcode=stitchcode([cell.code, cell.output.body])
			    push!(sections, Section(stitchedcode))
			end
		end
	end
	if !isempty(sections)
	    res=Page(sections, basename(fn))
	end
	
	return res
	
end
end

#export
begin

"""
> savepage(io, page::Page)--> Take the contents from a Page type and write to the io
"""
function savepage(io, page::Page)
		
	pageheading=uppercasefirst(Export.strip(Export.strip(page.name, r"[0-9_]"), r".jl"))

    println(io, "<h1>$pageheading</h1>")
	
	for section in page.sections
			println(io, section.line)
    end
		
end


"""
> savepage(page::Page, path::String)--> Given a Page type and the required path, creates the related markdwon file in the specified path. The name of the resulting markdown file is same as the nameof the notebook for which the document is generated
"""
function savepage(page::Page, path::String)
	fn=lowercase(Export.strip(Export.strip(page.name, r"[0-9_]"), r".jl"))
	open(joinpath(path, fn*".md"), "w") do io
        savepage(io, page)
    end
end
end

#export
begin			
"""
> export2md(fn::String, path::String)--> Generate document for a file in the given path
"""
function export2md(fn::String, path::String)
	nb=runandupdatenb(fn)
	page=createpage(fn, nb)
	if page != nothing
	    savepage(page, path)
	end
end

"""
> export2md(fns::AbstractVector, path::String)--> Map the `export2md(file, path)` to a given vector of file.
"""
function export2md(fns::AbstractVector, path::String)
	n = length(fns)
	p = Progress(n, 1)
	for fn in fns
	  next!(p)
      export2md(fn, path)
	end
end

"""
> export2md()--> Higher level API to generate documents for all the valid notebooks
"""
export2md(nbsdir)=export2md(Export.readfilenames(joinpath(pwd(), nbsdir)), "docs")
end

#export
export showdoc, export2md

#export
begin
"""
> export2readme()--> create readme from the contents of Index notebook
"""
function export2readme()
    cp(normpath(joinpath(".", "docs/index.md")), normpath(joinpath(".", "README.md")), force=true)
end 
end

end