import { downloadLocal, downloadBlock } from './utils/get';
import { get } from './utils/rc';
import ora from 'ora';
import inquirer from 'inquirer';
import fs from 'fs';
import chalk from 'chalk';
import symbol from 'log-symbols';

const util = require('util');
const exec = util.promisify(require('child_process').exec);

let block = async (action, blockName) => {
    let result = await get('block');
    switch(action) {
        case 'add': 
            if (fs.existsSync('block')) {
                await exec('rm -rf block');
            }
            if (!result.includes(blockName)) {
                console.log(symbol.error, chalk.red(`The blockName ${blockName} not exists`));
                return;
            }
            //命令行交互
            inquirer.prompt([
                {
                    name: 'destination',
                    message: 'Please enter the destination:(default src/view/) '
                }
            ]).then(async (answer) => {
                if (answer.destination && !fs.existsSync(answer.destination)) {
                    console.log(symbol.error, chalk.red('The destination not exists'));
                    return;
                }
                let loading = ora('downloading block ...');
                loading.start();
                downloadBlock().then(() => {
                    loading.succeed();
                    const destination = answer.destination ? `${answer.destination}` : 'src/view/';
                    exec(`cp -r block/${blockName} ${destination} && rm -rf block`);
                }, (e) => {
                    loading.fail(e.message);
                });
            });
            break;
        case 'list': 
            result.forEach(block => console.log(block + '\r'));
            break;
        default:
            break;
    }
}

module.exports = block;