/*
 * Created by Can Kuscu on 23/5/2018
 */

const util = require('util');
const EventEmitter = require('events').EventEmitter;
const moment = require('moment');
const path = require('path');
const clsPlayer = require('./clsPlayer').clsPlayer;
const Logger = require('../../logs/clsLogger').clsLogger;
const appRoot = process.cwd();
const _ = require('lodash');
const chalk = require('chalk');

const newPlaylistPlayer = class newPlaylistPlayer {
  constructor({ db } = {}) {
    this.playlistPlayerEvents = {
      stateChanged: 'stateChanged',
      positionChange: 'positionChange',
      fileChanged: 'fileChanged',
      playlistFinished: 'playlistFinished',
      fadeInStarted: 'fadeInStarted',
      fadeOutStarted: 'fadeOutStarted',
      vumeter: 'vumeter',
      Error: 'error'
    };
    this.db = db;
    this.logger = new Logger();
    this.volume = 0;
    this.channel = 0;
    this.channelCount = 2;
    this.defaultSoundCard = -1;
    this.player = new clsPlayer();
    this.flags = this.player.bassAttributes;
    this.mixer = 0;
    this.defaultFreq = 44100;
    this.playlist = [];
    this.songs = [];
    this.lastSong = '';
    this.duration = 0;

    this.player.on(this.player.playerEvents.positionChange, (position, duration, channel) => {
      let pos = moment({ hour: 0, minute: 0, second: 0 }).second(position).format("mm:ss");
      let dur = moment({ hour: 0, minute: 0, second: 0 }).second(duration).format("mm:ss");
      console.log(pos+'/'+ dur);
      this.duration = duration;
      pos = null;
      dur = null;
    });

    this.player.on(this.player.playerEvents.playbackFinished, async () => {
        let currentSong = await this.songs.shift();
        this.lastSong = currentSong;
        let songPath = path.join(appRoot, 'files', currentSong);
        this.channel = this.player.openFile(songPath, this.player.bassAttributes.BASS_STREAM_DECODE);
        this.player.addChannelToMixer(this.channel, this.player.bassAttributes.BASS_STREAM_DECODE);
        this.player.PlayMixer();  // remove sync and streamfree done in this method.
      });

    //todo: playlist finished, add new playlist or shuffle current.
    // this.player.on(this.player.eventTypes.playlistFinished, (channel) => {
    //
    // });
  }
  //------ end of constructor ------

  async start() {
    await this.playNextSong();
  }
  clearPlaylist() {
    this.songs = [];
  }

  getPlaylist(newPlaylist) {
    this.songs.push(newPlaylist);
  }

  createMixer(chanCount) {
    this.channelCount = chanCount;
    this.mixer = this.player.createMixer(this.channelCount, this.player.bassAttributes.BASS_STREAM_DECODE);
    return this.mixer;
  }
  //todo: needs fix.
  async playNextSong() {
    if(this.songs.length > 0) {
      this.songs = _.flatten(this.songs);
      let currentSong = await this.songs.shift(); // shift returns the first element of an array and returns that value
      this.lastSong = currentSong;
      let songPath = path.join(appRoot, 'files', currentSong);
      if(this.mixer == 0) {
        this.player.initSoundCard(this.defaultSoundCard, 0);
        this.mixer = this.player.createMixer(this.channelCount, this.player.bassAttributes.BASS_SAMPLE_FLOAT);
        this.channel = this.player.openFile(songPath, this.player.bassAttributes.BASS_STREAM_DECODE);
        this.player.addChannelToMixer(this.channel, this.player.bassAttributes.BASS_STREAM_DECODE);
        this.player.PlayMixer(); // remove sync and streamfree done in this method.
      }
      this.logger.AudioEvents(chalk.bgGreen('Playing: ' + currentSong));
    }
    this.emit(this.playlistPlayerEvents.playlistFinished);
  }
};

util.inherits(newPlaylistPlayer, EventEmitter);
module.exports = newPlaylistPlayer;