import * as path from 'path'
import { files } from '@plastichub/osr-cli-commons/glob'
import { Converter } from 'showdown'
const cheerio = require('cheerio')

export const addAssembly = (item) => `${item}/cad/**/Global*.+(SLDASM)`


export const componentContentOptions = (product) => {

    console.log('Create product compile options for ', product)

    product = '' + product

    const product_rel = product.replace('products/', '')

    return {
        debug: false,
        watch: false,
        root: '.',
        env: 'bazar-release',
        profile: '${root}/.osrl.json',
        output: '${product}/bazar/raw.html',
        format: 'html',
        module: 'plastichub-products',
        cwd: path.resolve('.'),
        cache: false,
        onCompiled: onComponent,
        onCompileDone: onComponentCompiled,
        variables: {
            product,
            product_rel,
            root: path.resolve('.'),
            product_relative: '' + product_rel
        }
    }
}

export const MainAssembly = (dir) => {
    const mains = files(dir, '**/cad/**/*Global*.+(SLDASM)') as string[]
    return mains[0];
}

export const file_path_with_ext = (file, ext) => {
    const parts = path.parse(file);
    return path.join(parts.dir, parts.name + '.' + ext);
}

export const unique_by = (arr, key) => {
    return [...new Map(arr.map(item => [item[key], item])).values()]
}

export const onComponent = (src, dst, content) => {
    const $ = cheerio.load(content, {
        xmlMode: true
    });

    $('a').each(function () {
        $(this).attr("style", "color:#4C74B9");
    })

    $('table').each(function () {
        $(this).attr("style", "display:table;width:auto;margin-left:auto;margin-right:auto");
    })

    return Promise.resolve($.html())
}

export const onComponentCompiled = (src, dst, options, content) => Promise.resolve()
