const fs  = require('fs-extra')
const path = require('path')
const _ = require('lodash')
const {v4} =require('uuid')
const merge = require('deepmerge')
const system = require('system-commands')
const deduplicateArray = require('deduplicate-array');
const beautify = require('js-beautify').js
const {
    glob,
    globSync,
    globStream,
    globStreamSync,
    Glob,
  } = require('glob')
const deepmerge = require('deepmerge')
function arrUnique(arr) {
    var cleaned = [];
    arr.forEach(function(itm) {
        var unique = true;
        cleaned.forEach(function(itm2) {
            if (_.isEqual(itm, itm2)) unique = false;
        });
        if (unique)  cleaned.push(itm);
    });
    return cleaned;
}
async function setDefaultCollection(){
    var sourceRootCollection =process.cwd() + '/node_modules/@bitev.io/core/features/collections'
    var localCollection = process.cwd()+'/collections'
    var tmpCollectionRoot = process.cwd()+'/.tmp/.cache/collections/'
     fs.copySync(sourceRootCollection,tmpCollectionRoot,{
        overwrite:true,
    })


   
return new Promise((resolve, reject) => {
glob(tmpCollectionRoot+'_v.*.js',{},async(err,files)=>{

    
    for await(var file of files){
        
        
            var name = path.basename(file)
            var localFileToKeep = path.resolve(__dirname,process.cwd()+`/collections/${name}`)

            var oldname = name.replace('_v.','')
            var localFileToDelete = path.resolve(__dirname,process.cwd()+`/collections/${oldname}`)

        

            
            // Merge old and current
            try{
                // root collection
                var rootCol = require(file) 
                var currentCol =null
                var currentCol =null
                // check if has old root named
                if(fs.pathExistsSync(localFileToDelete)){
                    currentCol = require(localFileToDelete)
                    fs.unlink(localFileToDelete)
                }
                 else{
                    fs.pathExistsSync(localFileToKeep) ? currentCol = require(localFileToKeep) : currentCol=rootCol
                }

              
                // set collection data
                var module_ = '@bitev.io/core/types'


               
                var newContent = merge(currentCol,rootCol)
                newContent.fields = arrUnique(newContent.fields);
                newContent.fields = deduplicateArray(newContent.fields,{
                    caseSensitive: false
                })
                




                let fileCol = `
                const { Collection } = require("${module_}");\n
                module.exports= Collection(
                 ${JSON.stringify(newContent)}
              )`
        
            
             
             
            
              // Write data in .js
            fs.writeFileSync(localFileToKeep,beautify(fileCol,{"indent_size": 4,}),()=>{})
           
        
            } catch(err){
                console.log(err)
                reject(err)
            }
      
    }

fs.removeSync(tmpCollectionRoot)
resolve()
})

})
}


function generateUID(config){
    var pathUID = process.cwd()+'/.tmp/.uuid'

    if(fs.existsSync(pathUID)){
        var uuid = fs.readFileSync(pathUID,"utf-8")
        
        config.uuid = uuid
    } else {
        fs.writeFileSync(pathUID,v4())
    }
}


async function generatePrismaQL(){
    await system('npx prisma generate').then(e=>{
       // console.log(e)
    }).catch(err=>{
        console.log(err)
    })

}


async function setFeature(config){
   
    if(process.env.NODE_ENV !== 'production'){
        generateUID(config)
         await setDefaultCollection()
         await generatePrismaQL()

    }

}


module.exports ={
    setFeature
}