const watchr  = require('watchr');
const fs      = require('fs')
const path    = require('path')
const ipcMain = require('electron').ipcMain;

var watch_event = null;

ipcMain
.on('watchr_event', (event, arg)=>{
  watch_event = event
})

class folderWatchr {
    constructor(folder) {
        this.folder = folder;
        this.files = [];
        var files = this.files;

        fs.readdirSync(this.folder).forEach(file => {
            files.push(folder + '/' + file);

        });
        for(var i = 0;i<files.length;i++){
            files[i]=files[i].replace(/\\/g, "/");
            watch_event.sender.send('watchr_file',{type:"add",file:files[i]});
        }

        function listener(changeType, fullPath, currentStat, previousStat) {
            console.log(changeType);
            fullPath = fullPath.replace(/\\/g, "/");
            switch (changeType) {
                case 'update':

                    break;
                case 'create':

                    console.log('the file', fullPath, 'was created', currentStat)
                    files.push(fullPath);
                    watch_event.sender.send('watchr_file',{type:"add",file:fullPath});
                    break;
                case 'delete':
                    watch_event.sender.send('watchr_file',{type:"remove",file:fullPath});
                    files.splice(files.indexOf(fullPath), 1);
                    break;
            }
        }

        function next(err) {
            if (err) return console.log('watch failed on', path, 'with error', err);
            console.log('watch successful on', path);
        }

        // Watch the path with the change listener and completion callback
        this.stalker = watchr.open(this.folder , listener, next);
    }
    destroy(){
        this.stalker.close()
    }
}

module.exports = folderWatchr;
