import * as path from 'path'

import { files, forward_slash } from '@plastichub/osr-cli-commons/glob'
import { IComponentConfig } from '@plastichub/osr-commons/'
import { isValidLibraryComponent, readOSRConfig } from '@plastichub/osr-fs-utils'
import { logger } from './'

import {
    productCADTask,
    productGitSyncTask
} from './component'

export const grunt = (grunt) => {
    grunt.initConfig({
        pkg: grunt.file.readJSON("package.json"),
        sshexec: {
            update: {
                debug: true,
                verbose: true,
                commands: 'sh update-osr.sh'
            }
        }
    })

    grunt.loadNpmTasks("grunt-extend-config")

    const cad_tasks = []
    const git_tasks = []

    const items = (category, includeProducts = false) => {
        const componentsPath = path.resolve(category)
        let components = files(componentsPath, '**/**/config.json') as string[]
        // components = components.filter(isValidLibraryComponent)
        components = components.filter((c) => {
            try {

                const config = readOSRConfig(c) as IComponentConfig
                if (config) {
                    if(config.forum ===false){
                        return false
                    }
                    if (!includeProducts) {
                        return !config.code && !config.cscartId && !config.steps
                    } else {
                    }
                }
                return true
            } catch (error) {
                logger.error(`Invalid config : ${c}`)
            }
        })
        return components
    }

    let components =
        [
            
            ...items('./injection/components',true),
            ...items('./extrusion/components',true),
            ...items('./sheetpress/components', true),
            ...items('./sheetpress/', true),
            ...items('./shredder',true),
            ...items('./injection'),
            ...items('./compression'),
            ...items('./extrusion')
        ]

    const root = path.resolve('.')
    components = components.filter(isValidLibraryComponent)
    components = components.map((c) => {
        const dir = path.relative(root, path.parse(c).dir)
        return forward_slash(dir)
    })

    const componentTasks = (items) => {
        items.forEach((i) => {
            productCADTask(grunt, i, {}, cad_tasks),
                productGitSyncTask(grunt, i, {}, git_tasks)
        })
    }

    logger.debug(`Registered component tasks for`, components)

    componentTasks(components)

    grunt.registerTask('components-update', [
        'components-cad',
        'components-git'
    ])

    grunt.registerTask('default', [
        'components-update'
    ])

    require("@plastichub/osr-tasks").initConfig(grunt, {})
}

module.exports = grunt