import * as path from 'path'

const fg = require('fast-glob')

import { sync as read } from '@plastichub/fs/read'
import { sync as write } from '@plastichub/fs/write'
import { sync as exists } from '@plastichub/fs/exists'
import { html_beautify } from 'js-beautify'
import { CONFIG_DEFAULT, IOSRConfig } from '@plastichub/osr-cli-commons'
import {  } from '@plastichub/osr-cli-commons/fs'

const cheerio = require('cheerio')

const mysql = require('mysql2')

import { logger } from './'

import { Converter } from 'showdown'

export const addAssembly = (item) => `${item}/cad/**/Global*.+(SLDASM)`

export const md2html = (content) => {
    let converter = new Converter({ tables: true });
    converter.setOption('literalMidWordUnderscores', 'true');
    return converter.makeHtml(content);
}

export const libraryContentOptions = (product) => {
    
    console.log('Create product compile options for ', product)
    product = ''  + product
    const product_rel = product.replace('products/','')
    return {
        debug: false,
        watch: false,
        root: '.',
        env: 'library-release',
        profile: '${root}/.osrl.json',
        output: '${product}/bazar/raw.html',
        format: 'html',
        module: 'osr-products',
        cwd: path.resolve('.'),
        cache: false,
        onCompiled: onProduct,
        onCompileDone: onProductCompiled,
        variables: {
            product,
            product_rel,
            root: path.resolve('.'),
            product_relative: '' + product_rel
        }
    }
}

export const forward_slash = (path) => {
    const isExtendedLengthPath = /^\\\\\?\\/.test(path);
    const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex

    if (isExtendedLengthPath || hasNonAscii) {
        return path;
    }

    return path.replace(/\\/g, '/');
};

export const files = (dir, glob) => fg.sync(glob, {
    dot: true,
    cwd: dir,
    absolute: true
});

export const MainAssembly = (dir) => {
    const mains = files(dir, '**/cad/**/*Global*.+(SLDASM)');
    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 onProduct = (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())
}

const update = async (dbconfig, description, id) => {
    return new Promise((resolve, reject) => {
        const connection = mysql.createConnection(dbconfig);
        var sql = mysql.format('UPDATE cscart_product_descriptions SET full_description = ? WHERE cscart_product_descriptions.product_id = ?',
            [description, id]
        );
        connection.query(
            sql,
            function (err, results) {
                if (err) {
                    logger.error('SQL Error', err.message);
                    reject(err);
                } else {
                    resolve(results)
                }                
            }
        );
    })
}

export const onProductCompiled = (src, dst, options, content) => {
    const config: any = read(path.resolve(options.variables.product + '/config.json'), 'json');

    content = html_beautify(md2html(content))
    write(path.resolve(options.variables.product + '/bazar/output.html'), content)

    const cscartId = config.cscartId
    if (!cscartId) {
        logger.error(`Have no cscart id for ${config.slug}`)
        return
    }
    const osrConfig = CONFIG_DEFAULT() as IOSRConfig    

    if (osrConfig.cscart.mysql) {
        return new Promise((resolve) => {
            update(osrConfig.cscart.mysql, content, cscartId).then((result) => {
                logger.debug('updated cscart ' + config.name)
                resolve(1)
            }).catch((e) => {
                logger.error('Error updating CSCart', e)
            })
        })
    }else{
        logger.error('Have no CSCart Mysql config !')
    }
    return Promise.resolve()
}
