var path = require('path');
var fs = require('fs-extra');
var _ = require('underscore');
var UPLOAD_DIR = require('../upload').UPLOAD_DIR;
var EVENT_IMG_DIR = './public/img/events';
var async = require('async');
var Event = require('../../models/Event');
var Image = require('../../models/Image');

exports.createEvent = function(req, res, next) {
    var data = req.body;
    console.log('Create event request ', data);

    var images = req.body.images || [];
    async.map(images, verifyAndCopyImage, buildAndSaveEvent(req, res, next));
};

function buildAndSaveEvent(req, res, next) {
    return function(err, images) {
        if (err) return next(err);
        console.log('Copied images ', images);
        var event = new Event({
            name: req.body.name,
            author: req.user._id,
            description: req.body.description,
            activity: req.body.activity,
            place: {
                name: req.body.place.name,
                latitude: req.body.place.latitude,
                longitude: req.body.place.longitude
            },
            start: {
                date: req.body.start.date,
                time: req.body.start.time
            },
            end: {
                date: req.body.end.date,
                time: req.body.end.time
            },
            images: _.map(images, function(image){
                return new Image(image);
            })
        });
        console.log('Saving event ', event);
        event.save(function(err) {
            if (err) return next(err);
            res.send(event);
        });
    }
};

exports.verifyAndCopyImage = function(opts) {
    var uploadDir = opts.uploadDir;
    var eventImgDir = opts.eventImgDir;

    return function(image, next) {
        console.log('Verify image ', image);
        var imagePath = path.join('/', image.path); // removes any '..'
        fs.exists(imagePath, function(exists) {
            console.log('Image exists ', exists);
            console.log('uploadDir ', uploadDir);
            if (exists && imagePath.indexOf(uploadDir) == 0) {
                var imageName = path.basename(imagePath);
                var copyTo = path.join(eventImgDir, imageName);
                console.log('Copy ', imagePath, ' to ', copyTo);
//                fs.rename(imagePath, copyTo, function(err) {
//                    next(null, _.extend(image, {path: copyTo}));
//                });
                // TODO replace with fs.copy()
                fs.mkdirp(eventImgDir, function(err) {
                    if (err) next(err);

                    var wstream = fs.createWriteStream(copyTo);
                    var rstream = fs.createReadStream(imagePath);
                    rstream.pipe(wstream);
                    rstream.on('error', next);
                    wstream.on('error', next);
                    rstream.on('end', onCopyEnd);
                    function onCopyEnd() {
                        var copiedImage = _.extend(image, {path: copyTo});
                        fs.unlink(imagePath, function(err) {
                            if (err)
                            console.error('Cannot unlink file ', imagePath, err);
                        });
                        next(null, copiedImage);
                    }
                });
            } else {
                next(null, image);
            }
        });
    };
};

var verifyAndCopyImage = exports.verifyAndCopyImage({uploadDir: UPLOAD_DIR, eventImgDir: EVENT_IMG_DIR});
@@ -2221,83 +2221,15 @@
     
-console.log('Copy ', imagePath, ' to ', copyTo);%0A//                fs.renam
+moveFil
 e(im
@@ -2261,18 +2261,16 @@
 (err) %7B%0A
-//
         
@@ -2286,20 +2286,19 @@
    next(
-null
+err
 , _.exte
@@ -2325,18 +2325,16 @@
 yTo%7D));%0A
-//
         
@@ -2361,97 +2361,51 @@
     
-    // TODO replace with fs.copy()%0A                fs.mkdirp(eventImgDir, function(err) %7B
+%7D else %7B%0A                next(null, image);
 %0A   
@@ -2409,32 +2409,34 @@
             
+%7D%0A
         
 if (err) nex
@@ -2427,480 +2427,205 @@
     
-if (err) next(err
+%7D
 );%0A
-%0A
     
-                var wstream = fs.createWriteStream(copyTo);%0A                    var rstream = fs.createReadStream(imagePath);%0A                    rstream.pipe(wstream);%0A                    rstream.on('error', next);%0A                    wstream.on('error', next);%0A                    rstream.on('end', onCopyEnd);%0A                    function onCopyEnd() %7B%0A                        var copiedImage = _.extend(image, %7Bpath: copyTo%7D);%0A                
+%7D;%0A%7D;%0Afunction moveFile(srcPath, destPath, next) %7B%0A    console.log('Moving ', srcPath, ' to ', destPath);%0A    fs.copy(srcPath, destPath, function(err) %7B%0A        if (err) return next(err);%0A%0A
     
@@ -2638,21 +2638,19 @@
 .unlink(
-image
+src
 Path, fu
@@ -2679,32 +2679,16 @@
     
-          
-      
 if (err)
 %0A   
@@ -2683,29 +2683,19 @@
 if (err)
-%0A            
+ %7B%0A
         
@@ -2739,21 +2739,19 @@
 file ', 
-image
+src
 Path, er
@@ -2770,34 +2770,10 @@
     
-           
- %7D);%0A          
+%7D%0A
     
@@ -2772,34 +2772,32 @@
   %7D%0A            
-  
 next(null, copie
@@ -2793,157 +2793,32 @@
 null
-, copiedImage);%0A                    %7D%0A                %7D);%0A            %7D else %7B%0A                next(null, image);%0A            %7D%0A        %7D);%0A    %7D;%0A%7D;
+);%0A        %7D);%0A    %7D);%0A%7D
 %0A%0Ava

Refactor create-event