'use strict';

const find = require('find');
const fs = require('fs-extra');
const jsonFile = require('jsonfile');
const path = require('path');
const chalk = require('chalk');
const behaveConvert = require('./behave-to-cucumber');

module.exports = function collectJSONS(options) {
    const jsonOutput = [];
    let files;

    try {
        files = [];
        let rootFiles=fs.readdirSync(path.resolve(process.cwd(), options.jsonDir));
        if(rootFiles.length>0){
            rootFiles.forEach(function(item,index){
               let extName= path.extname(item);
               if(extName===".json"){
                let json_file=  path.join(path.resolve(process.cwd(), options.jsonDir),item)
                files.push(json_file)
               }

            })
        }
        

    } catch (e) {
        throw new Error(`There were issues reading JSON-files from '${options.jsonDir}'.`);
    }

    if (files.length > 0) {

        files.map(file => {
            // Cucumber json can be  empty, it's likely being created by another process (#47)
            const data = fs.readFileSync(file).toString() || "[]";

            JSON.parse(data).map(json => {
                if (options.metadata && !json.metadata) {
                    json.metadata = options.metadata;
                } else {
                    json = Object.assign({
                        "metadata": {
                            "browser": {
                                "name": "not known",
                                "version": "not known"
                            },
                            "device": "not known",
                            "platform": {
                                "name": "not known",
                                "version": "not known"
                            }
                        }
                    }, json);
                }

                behaveConvert(json)

                jsonOutput.push(json)
            });
        });

        if (options.saveCollectedJSON) {
            const file = path.resolve(options.reportPath, 'merged-output.json');
            fs.ensureDirSync(options.reportPath);
            jsonFile.writeFileSync(file, jsonOutput, {spaces: 2});
        }

        return jsonOutput;
    }

    console.log(chalk.yellow(`WARNING: No JSON files found in '${options.jsonDir}'. NO REPORT CAN BE CREATED!`));
    return [];
};
