const fs = require('fs')
const path = require('path')

const BlockFactory = require('./../factories/block.js')

/**
 *  search, filter and find pages
 *
 *
 *  @author Björn Hase <me@herr-hase.wtf>
 *  @license http://opensource.org/licenses/MIT The MIT License
 *  @link https://gitea.node001.net/HerrHase/siteomat-webpack-plugin.git
 *
 */

class Blocks {

    /**
     *
     *
     *  @param {string} dirPath
     *
     */
    constructor(dirPath, filename) {

        this.FILE_EXTENSION   = '.md'
        this.DIRECTORY_BLOCKS = '_blocks'

        this._dirPath = dirPath

        // if filename is not index.md add filename to path
        if (filename !== 'index.md') {
            this._dirPath += '/' + filename
        }

        this._dirPath += '/' + this.DIRECTORY_BLOCKS;
        this._results = {}
    }

    /**
     *
     *
     *  @return {array}
     */
    find() {
        if (fs.existsSync(this._dirPath)) {
            this._findFiles(this._dirPath)
        }

        return this._results
    }

    /**
     *  find files
     *
     *  @param  {string} dirPath
     *  @param  {Object} [parent = '']
     *
     */
    _findFiles(dirPath, parent = '') {

        // getting block files
        const files = fs.readdirSync(dirPath, {
            withFileTypes: true
        })

        files.forEach((file) => {

            // skip for file that is not markdown
            if (file.isFile() && path.extname(file.name) !== this.FILE_EXTENSION) {
                return
            }

            // get file
            const fileString = this._getFile(file, dirPath + parent)

            // skip if empty
            if (!fileString) {
                return
            }

            // create page object and add to page
            const block = new BlockFactory(fileString, this._dirPath)
            const blockname = this._parseBlockname(file.name)

            if (this._isArray(file.name)) {
                if (!this._results[blockname]) {
                    this._results[blockname] = []
                }

                this._results[blockname].push(block.get())
            } else {
                this._results[blockname] = block.get()
            }
        })
    }

    /**
     *  remove '.md' and also ordering number = filename
     *
     *  @param  {string} filename
     *  @return {string}
     *
     */
    _parseBlockname(filename) {
        const regex = new RegExp(/[-_]?[0-9]*\b.md\b$/)
        return filename.replace(regex, '')
    }

    /**
     *  remove '.md' and also ordering number = filename
     *
     *  @param  {string} filename
     *  @return {string}
     *
     */
    _isArray(filename) {
        const regex = new RegExp(/[-_]?[0-9]\b.md\b$/)
        return regex.test(filename)
    }

    /**
     *  get file content
     *
     *  @param  {string} slug
     *  @param  {string} sourcePath
     *  @return {mixed}
     *
     */
    _getFile(file, dirPath) {

        // file
        let result = null

        // path of file, first try with slug
        let filePath = dirPath + '/' + file.name

        if (fs.existsSync(filePath) && file.isFile()) {
            result = fs.readFileSync(filePath, 'utf8')
        }

		return result
	}

}

module.exports = Blocks
