var fs = require('fs-extra');
var p = require('path');
var sprintf = require("sprintf-js").sprintf;

var walk = require('walkdir');
var async = require('async');
var Promise = require('promise');
var find = require('array-find');

var gtc = require('./gtc');
var util = require('./util');

module.exports.writeShowInfo = function(record) {

    console.log(sprintf('   Removing old metadata...'));
    walk.sync(record.dir)
        .forEach(function(file) {
            //console.log(file, p.extname(file));
            if (p.extname(file) === '.nfo') {
                fs.removeSync(file);
            }
        });

    return gtc
        .getCourseDetails(record.match)
        .then(function(data) {
            var show = data;

            var episodeFiles = walk.sync(record.dir)
                .filter(function(file) {
                    return p.extname(file) === '.mkv';
                });
            var basefolder = record.dir + p.sep;

            // output tvinfo.nfo file
            console.log(sprintf('   Writing metadata...'));
            fs.outputFileSync(basefolder + show.getFileName(), show.toXML(), 'utf8');

            return processEpisodes(show, episodeFiles, basefolder)
                .then(function() {
                    console.log(sprintf('   Fetching images...'));
                    
                    //console.log('poster');        
                    
                    return getPoster(show, basefolder);
                })
                .then(function() {
                    //console.log('fanart');
                    return getFanart(show, basefolder);
                })
                .then(function() {
                    //console.log('move');
                    return moveShow(record.dir, p.dirname(record.dir) + p.sep + show.getShowTitle());
                });
            
        })
        .then(function() {
            console.log('All done.');
        });
};

function processEpisodes(show, episodeFiles, basefolder) {
    return new Promise(function(fulfill, reject) {
        async.eachSeries(show.episodes, function(episode, callback) {
            
            //console.log(episode);
            
            //show.episodes.forEach(function(episode) {
            var episodeFile = find(episodeFiles, function(file) {
                var reg = new RegExp('.*' + episode.getEpisodeNumber() + '.*', 'ig');
                //console.log(p.basename(file), reg.test(p.basename(file)), reg);
                return reg.test(p.basename(file));
            });

            if (episodeFile) {
                fs.outputFileSync(basefolder + episode.getFileName(), episode.toXML(), 'utf8');

                var newEpisodeFile = basefolder + episode.getFileName(p.extname(episodeFile));

                //move episode files
                if (!fs.existsSync(newEpisodeFile)) {
                    fs.move(episodeFile, newEpisodeFile, {}, function(err) {
                        if (err) {
                            console.error(err);
                        }
                        callback();
                    });
                }
                else {
                    callback();
                }
            }
            else {
                callback();
            }
            //});
        }, function(err) {
            if (err) {
                console.error(err);
            }
            console.log(sprintf('   All episodes are processed.'));
            fulfill();
        });
    });
}

function getPoster(show, basefolder) {
    // get poster image, crop it and multiply
    return util.downloadFile(show.images.packageLarge, basefolder + show.getPosterFileName())
        .then(function() {
            return util.cropPoster(basefolder + show.getPosterFileName());
        })
        .then(function() {

            fs.copySync(basefolder + show.getPosterFileName(), basefolder + show.getPosterFileName('season01-'));
            fs.copySync(basefolder + show.getPosterFileName(), basefolder + show.getPosterFileName('season-all-'));
            //console.log('poster done');
        });
}

function getFanart(show, basefolder) {
    // get fanart image and multiply
    if (show.images.baseImages.length > 0) {
        return util.downloadFile(show.images.baseImages[0], basefolder + show.getFanartFileName())
            .then(function() {
                fs.copySync(basefolder + show.getFanartFileName(), basefolder + show.getFanartFileName('season01-'));
                fs.copySync(basefolder + show.getFanartFileName(), basefolder + show.getFanartFileName('season-all-'));

                //console.log('fanart done');
            });
    }
}

function moveShow(src, dest) {
    // moving base folder
    if (!fs.existsSync(dest)) {

        return new Promise(function(fulfill, reject) {
            fs.move(src, dest, function() {
                //console.log('move done');
                fulfill();
            });
        });
    }
}
@@ -1300,36 +1300,16 @@
 ...'));%0A
-                    
 %0A       
@@ -1349,37 +1349,9 @@
 r');
-        %0A                    
+%0A
 %0A   
@@ -1777,29 +1777,17 @@
     %7D);%0A
-            
 %0A
+
         
@@ -2050,29 +2050,17 @@
 back) %7B%0A
-            
 %0A
+
         
@@ -2091,21 +2091,9 @@
 e);%0A
-            
 %0A
+
     
@@ -2773,32 +2773,34 @@
                 
+//
 fs.move(episodeF
@@ -2832,32 +2832,107 @@
 function(err) %7B%0A
+                    fs.rename(episodeFile, newEpisodeFile, function(err) %7B%0A
                 
@@ -4707,16 +4707,44 @@
  folder%0A
+    //console.log('moving')%0A
     if (
@@ -4838,19 +4838,21 @@
      fs.
-mov
+renam
 e(src, d
@@ -4932,32 +4932,32 @@
      fulfill();%0A
-
             %7D);%0A
@@ -4947,32 +4947,166 @@
 %0A            %7D);
+%0A%0A            /*fs.move(src, dest, function() %7B%0A                console.log('move done');%0A                fulfill();%0A            %7D);*/
 %0A        %7D);%0A   

use rename instead of move