const util = require('util');
const EventEmitter = require('events').EventEmitter;

class clsIceCast {
    constructor() {
        this.bass = require('./basswrapper').basswrapper;
        this.basslib = new this.bass();
        this.Logger = require('../../logs/clsLogger').clsLogger;
        this.logger = new this.Logger();
        this.serverAdress = 'http://carrefour.smg.com.tr:8000/cantest';
        this.serverPassword = '1q2w3e';
        this.serverPort = 8000;
        this.encodeType = this.basslib.BASS_ENCODE_TYPE_MP3;
        this.serverName = '';
        this.url = '';
        this.genre = '';
        this.desc = '';
        this.serverHeader = '';
        this.sampleRate = 44100;
        this.isPublic = true;
        this.flags = 0;
        this.mixer = 0;
        this.channelCount = 0;
        this.iceCastEnabled = true;
        this.encoderChannel = 0;
        this.lameOptions = 'lame -r -V 2 -b';
        this.bitrate = '56';
        this.status = 0;
        this.checkServerTimeOut = 5000;
    }

    initSoundCard() {
        let init = this.basslib.BASS_Init(-1, this.sampleRate, this.basslib.BASS_DEVICE_STEREO);
        if (!init) {
            console.log('err', this.basslib.BASS_ErrorGetCode());
        } else {
            console.log('init success');
        }
    }

    checkServer() {
        let status = this.basslib.BASS_Encode_IsActive(this.encoderChannel);
        let err = this.basslib.BASS_ErrorGetCode();
        if (status != 1) {
            this.logger.iceCast('Icecast is not running, restarting server');
            setTimeout(this.iceCastStream(this.mixer), 1000);
        }
    }

    iceCastStream(mixer) {
        this.mixer = mixer;
        this.encoderChannel = this.basslib.BASS_Encode_Start(this.mixer, this.lameOptions + this.bitrate + ' -', this.basslib.BASS_ENCODE_NOHEAD);
        let castInit = this.basslib.BASS_Encode_CastInit(this.encoderChannel, this.serverAdress, this.serverPassword, this.encodeType, this.serverName, this.url, this.genre, this.desc, this.serverHeader, this.sampleRate, this.isPublic);
        let err = this.basslib.BASS_ErrorGetCode();

        if (err != 0) {
            this.logger.iceCast('icecast err: ', err);
        }
        // BASS_ERROR_CAST_DENIED	2100	BassEnc: Access denied (invalid password)/**/
        // if (err == 2100) {
        //     this.logger.iceCast('Icecast err: Access denied. Invalid password');
        // }
        if (err == 40 || castInit == 40) {
            this.logger.iceCast('Server is not running, time out error');
            setTimeout(this.iceCastStream(this.mixer), this.checkServerTimeOut);
        }
        setInterval(() => {
            this.checkServer();
        }, this.checkServerTimeOut);
    }
}

util.inherits(clsIceCast, EventEmitter);
module.exports = {
    clsIceCast: clsIceCast
};
