var mongoose = require('mongoose'),
  Schema = mongoose.Schema,
  ItunesTrack = require('../models/itunes-track');

var ItunesLibrarySchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  updated: Date,
  path: {
    type: String,
    default: process.env.HOME + '/Music/iTunes/iTunes\ Library.xml'
  },

});

ItunesLibrarySchema.methods.updateFromXML = function() {
  const itunesLibrary = this,
    fs = require('fs'),
    itunes = require('itunes-data'),
    parser = itunes.parser(),
    stream = fs.createReadStream(process.env.HOME + '/Music/iTunes/iTunes\ Library.xml')
    trackArray = [];

//https://www.npmjs.com/package/simple-plist

  parser.on('track', function(track) {
    if (track.Kind == 'Fichier audio MPEG') {
      saveItunesObjectToMongo(track);
      trackArray.push(track['Persistent ID']);
    }
    return true;
  });

  parser.on('end', () => {
    removeOrphanTracks(trackArray);
    ItunesTrack.count({}, function( err, count){
      console.log('--------- Number of itunesTrack -----');
      console.log( 'Number of ItunesTrack:', count );
    });

  });

  stream.pipe(parser);



  return true;
};

function itunesFieldToMongo(field) {
  return field.replace(/ /g,'_').toLowerCase();
}

function promisify(fn) {
  return (...args) => new Promise((resolve, reject) => {
    args.push((err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
    fn.apply(null, args);
  });
}

function removeOrphanTracks(importedTracksArray) {
  ItunesTrack.find({}).exec(function(err, tracksInDb) {
    for(const index in tracksInDb) {
      if (importedTracksArray.indexOf(tracksInDb[index].persistent_id) === -1) {
        ItunesTrack.find({persistent_id: tracksInDb[index].persistent_id}).remove().exec();
      }
    }
  });

}

function saveItunesObjectToMongo(object) {
  const itunesTrackObject = {};
  for (var key in object) {
    itunesTrackObject[itunesFieldToMongo(key)] = object[key];
  }

  ItunesTrack.findOneAndUpdate(
    {
      persistent_id: object['Persistent ID']
    },
    {
      $set: itunesTrackObject
    },
    {
      new: true,
      upsert: true
    }, function(err, itunesTrack) {
    if(err){
        console.log('Something wrong when updating data!');
    }
  });

  // getItunesRating(object['Persistent ID'])
  //   .then(rating => {
  //     itunesTrackObject['rating'] = rating
  //     ItunesTrack.findOneAndUpdate(
  //       {
  //         persistent_id: object['Persistent ID']
  //       },
  //       {
  //         $set: itunesTrackObject
  //       },
  //       {
  //         new: true,
  //         upsert: true
  //       }, function(err, itunesTrack) {
  //       if(err){
  //           console.log('Something wrong when updating data!');
  //       }
  //     });
  //   })
  //   .catch((err) => {
  //
  //   });
}

// https://dzone.com/articles/understanding-execfile-spawn-exec-and-fork-in-node?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed:%20dzone%2Fwebdev
const execAsync = promisify(require('child_process').exec);
function getItunesRating(persistentID) {
  return execAsync('osascript -l JavaScript -e \'Application("iTunes").tracks.whose({persistentID : "' + persistentID + '"}).rating();\'')
    .then((stdout) => {
      if (stdout) {
        var output = parseInt(stdout.trim());
        return output;
      }
      return 0;
    });
}

module.exports = mongoose.model('ItunesLibrary', ItunesLibrarySchema);
