var fs = require('fs');
var id3 = require('id3js');
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var fileExists = require('./fileExists');
var filterFileList = require('./filterFileList');

/**
* Tries to get album info based on mp3s found in directory
* @param {string} directory (eg. /path/to/music)
* @param {albumInfo~requestCallback} callback
*/
module.exports = function (directory, callback) {
    var albumData = {}, ffProbeIndex = 0;
    filterFileList(directory, 'mp3', function (err, data) {
		if (err) {
			callback(err, null);
			return;
		}

		if(data.length > 0) {
			//try to get info from first mp3 found
			id3({ file: path.join(directory, data[0]), type: id3.OPEN_LOCAL }, function(err, tags) {
				if (err) {
					callback(err, null);
					return;
				}

				albumData.artist = tags.artist;
				albumData.album = tags.album;
				
				//looks for folder.jpg for album art
				//todo: make this configurable or search online maybe?
				albumData.albumArt = path.join(directory, 'folder.jpg');
				if(!fileExists(albumData.albumArt)) {
					albumData.albumArt = path.resolve(__dirname, 'default.jpg');
				}
				
				albumData.tracks = [];
				data.forEach(function(filename, index, array) {
					ffmpeg.ffprobe(path.join(directory, filename), function(err, metadata) {
						ffProbeIndex++;
						if(err) {
							if (ffProbeIndex >= array.length) {
								callback(err, albumData);
							}
							return;
						}
						var track = {
							title: '',
							path: path.join(directory, filename),
							trackNumber: 0,
							duration : metadata.format.duration
						};
						var ftags = metadata.format.tags;
						if(ftags) {
							if(ftags.title) {
								track.title = ftags.title;
							}
							
							if(ftags.track) {
								//track could be number or number/total
								if(ftags.track.indexOf('/') > -1) {
									track.trackNumber = parseInt(ftags.track.split('/')[0], 10);
								} else {
									track.trackNumber = parseInt(ftags.track, 10);
								}
							}
						}
						albumData.tracks.push(track);
						if (ffProbeIndex >= array.length) {
							albumData.tracks.sort(function(a, b) {
								if(b.trackNumber > a.trackNumber) {
									return -1;
								}
								if(b.trackNumber < a.trackNumber) {
									return 1;
								}
								return 0;
							});
							callback(err, albumData);
						}
					});
				});
				
				
				//callback(err, albumData);
			});
		}
	});
} 

/**
 * This callback is displayed as part of the albumInfo class.
 * @callback albumInfo~requestCallback
 * @param {null|*} err
 * @param {{artist: string, album: string, albumArt: string, tracks : array}|null} albumData 
 */