import os, re
from os import path
from natsort import natsorted
from generator import library, helper, format, header, qms, whitelist

def core(cardDirs, localroot=os.getcwd()):

    sections, ignore = library.get_sections(cardDirs)
    localIndexArr, orderArr = library.get_indexArr(sections)

    wl = ''

    index = library.generate_index_top()

    for folder in cardDirs:
        # FolderFlag gets set to true at the first iteration
        folderFlag = True

        # check if folder exists
        if path.isdir(folder) and folder not in ignore:
            dirs = os.listdir(folder)
            dirs = natsorted(dirs)

            for d in dirs:
                if d[0] != "." and d not in ignore and helper.has_subdirs(folder + "/" + d):
                    # get the index of the section
                    indexS = sections.index(d)
                    maxOrder = 0

                    if len(localIndexArr[indexS]) == 0:
                        localIndexArr[indexS] = ["\n"]

                    for root, dirs, files in os.walk(folder+"/"+d):
                        for file in files:
                            if file.endswith(".md"):
                                fileName = os.path.join(root, file)
                                # ignore subsections (.md files that start with _)
                                if file[0] != "_":
                                    print(" > Generating header for: " + fileName)

                                    # save order and legacy section
                                    order = library.save_tag(localroot, root, file, "card_order")
                                    legacy_from = library.save_legacy_from(localroot, root, file)
                                    description = library.save_tag(localroot, root, file, "description")

                                    # extract the title from the QMS metadata
                                    title, qms_yml, yml_file = library.get_title(localroot, root, file)
                                    name = ""
                                    nb = ""

                                    if qms_yml:
                                        name = library.save_tag(localroot, root, yml_file, "name")

                                        # determine the latest version number
                                        nb = library.save_tag(localroot, root, yml_file, "history", "version")

                                        # prepare the MD version of the QMS document
                                        qms.prepare_qms(localroot, root, file, nb)

                                    # remove the previous header
                                    n = header.remove_header(localroot, root, file)

                                    # generate a permalink
                                    permalink = "/" + root + "/"

                                    # generate the shortcut
                                    shortcut = re.sub(folder, '', root)

                                    # remove the first /
                                    shortcut = shortcut[1:]

                                    # replace the / with a :
                                    shortcut = re.sub('/', ':', shortcut)

                                    if len(order) > 0:
                                        # find the maximum of existing orders
                                        if folderFlag:
                                            if len(orderArr[indexS]) > 0:
                                                maxOrder = max(orderArr[indexS])
                                            else:
                                                maxOrder = 0
                                            # after determining the max order, set the folder flag to False to avoid another entry into the same block of code
                                            folderFlag = False

                                        tmp = orderArr[indexS].copy()
                                        tmp.append(maxOrder + int(order))
                                        orderArr[indexS] = tmp
                                    else:
                                        orderArr[indexS] = []


                                    # generate the header for each card
                                    h = header.generate_header(folder, permalink, shortcut, order, legacy_from, title, description, name, nb)

                                    # add autogenerated links to whitelist
                                    wl += whitelist.generate_whitelist_entry(folder, permalink, shortcut)

                                    # add the header properly speaking
                                    format.line_prepender(fileName, h)

                                    localIndexArr[indexS].append(format.build_link(title, root))

                                    # output
                                    print(" + New header added.")
                                    print("-----------------------")

    localIndexArr = library.sort_sections(sections, localIndexArr, orderArr)

    index = library.generate_index(index, sections, localIndexArr)

    return index, wl