const {v4:uuid} = require("uuid")
const {cleanURL,cleanPath, imageToBase64} =require('../utilities/utils')
const fileUpload = require('express-fileupload');
const express = require('express')
const {sendToFtp} =require('./ftp')
const { expressSharp, FsAdapter, HttpAdapter } =require('express-sharp');
const fs = require('fs')
const _ =require('lodash')
function loaduploadExpress(config){
    config.upload_dir = cleanPath(process.cwd()+'/uploads/')
    var upload_dir = cleanPath(process.cwd()+'/uploads/')
    var api = config.api
    
    config.app.use(
        '/v1/assets/transform/',
        expressSharp({
          imageAdapter: new FsAdapter(upload_dir),
        })
      )
    config.app.use("/v1/assets/", express.static(upload_dir,{
        maxAge:86400000 ,// 24h
        
    })); // Static file dir
    config.app.use(fileUpload())
    config.app.get('/v1/assets/download', (res,req)=>{
        let filedisk = req.query.filedisk || null
        if(!filedisk){

            return res.status(400).send({
                error:"No filename on disk"
            })
        } else {

          var pathFile =cleanPath(process.cwd()+'/uploads/'+filedisk)
          return res.download(pathFile)
            
        }



    })

    config.app.post('/__upload__/',async(req,res)=>{

       var data_ =  JSON.parse(req.body?.data) ||{}
       var ref_ = req.body?.ref ||null
       var title = req.body?.title ||null
       var description = req.body?.description ||null
       var base64 = null

        if(!api.isSet('medias')) {
            consola.error("Medias model not found")
            return res.status(400).send("medias Model not found")
        }

        var files = req.files || null
       

        if(!files || Object.keys(files).length === 0){

           return res.status(400).send("No fileds where uploaded")
        }
      
     try{

        files = files.files // Get instance .files
        if(!Array.isArray(files)){ // Single file
            let url =(uuid()+'.'+files?.name).replace(/\s/g, '')
            let fileDisk = config.upload_dir+'/'+url
            await files.mv(fileDisk)

            if(data_?.driver=='ftp'){
            await sendToFtp(fileDisk,url,config)
            }

            if(files.mimetype.match(/(image)/) && config?.upload?.enableBase64){
                
                base64 =imageToBase64(fileDisk,{
                    mimeType:files.mimetype,
                    usePrefix:true
                })
                
            }

            var response = await api.create("medias",{
                data:{
                    title:title,
                    description:description,
                    ref:ref_ ||null,
                    driver:data_.driver || 'local',
                    filename:files?.name||null,
                    filedisk:url,
                    asseturl:config.upload?.ftp?.assetURL||null,
                    details:{
                        name:files.name||null,
                        size:files?.size||null,
                        mimeType:files?.mimetype||null,
                        md5:files?.md5||null,
                        base64:base64
                    },
                    data:_.omit(data_,['ref'])||null,
                }
            },
            req,
            config
            
            )




           } else { // Multiple files
            var response=[]
         
            for await (var file of files){
                let url =(uuid()+'.'+file?.name).replace(/\s/g, '')
                let fileDisk = config.upload_dir+'/'+url
                var base64=null
                
                await file.mv(fileDisk)
                if(data_?.driver=='ftp'){
                   await sendToFtp(fileDisk,url,config)
                }
                if(file.mimetype.match(/(image)/) && config?.upload?.enableBase64){
                    base64 =imageToBase64(fileDisk,{
                        mimeType:file.mimetype,
                        usePrefix:true
                    })
                    
                }
                await api.create("medias",{
                    data:{
                        title:title,
                        description:description,
                        ref:ref_ ||null,
                        driver:data_.driver || 'local',
                        filename:file?.name||null,
                        filedisk:url,
                        asseturl:config.upload?.ftp?.assetURL||null,
                        details:{
                            name:file.name||null,
                            size:file?.size||null,
                            mimeType:file?.mimetype||null,
                            md5:file?.md5||null,
                            base64:base64
                        },
                        data:_.omit(data_,['ref'])||null,
                    }
                },req,config).then(e=>{
                    response.push(e)
                })
    
            }
    
    
           }

           if(config.debug){
            //consola.success('Uploaded OK',response)
           }

          

           res.send(response)

     } catch(err){

        config.debug ? consola.error(err):null
        res.status(400).send({
            error:String(err)
        })


     }


        
        




       



    })

}

async function unlinkMedia(medias,config,req,options,api){
    var mediasToRemove =medias
    try{ // Remove 

    
         mediasToRemove.map(media=>{
           // console.log("Remove",media.fileDisk)
            var fileOnDisk = config.upload_dir+'/'+media.filedisk
            fs.unlinkSync(fileOnDisk)
           })
    
        

    
      } catch(err){
        console.log(err)
    
      }
    
      

}


module.exports={

    loaduploadExpress,
    unlinkMedia
}