/*!
 * Modified Recorder.js to create small-sized recorded audio
 * Copyright (c) 2013 Matt Diamond
 * Licensed under MIT (https://github.com/mattdiamond/Recorderjs/blob/master/README.md)
 */

'use strict';
import _ from 'lodash';

export class RecorderLib {
    config: any = {
        bufferLen: 2048,
        numChannels: 1, //1 channel to reduce audio size
        mimeType: 'audio/wav'
    };

    recording = false;
    worker: any;

    constructor(cfg, sampleRate) {
        this.config = _.assign(this.config, cfg);
        this.onaudioprocess = this.onaudioprocess.bind(this);

        this.worker = (function() {
            let recLength = 0;
            let recBuffers: any = [];
            let sampleRate;
            let numChannels;

            return {
                init(config) {
                    sampleRate = config.sampleRate;
                    numChannels = config.numChannels;
                    initBuffers();
                },
                record(inputBuffer) {
                    for (let channel = 0; channel < numChannels; channel++) {
                        recBuffers[channel].push(inputBuffer[channel]);
                    }
                    recLength += inputBuffer[0].length;
                },
                exportWAV(type, cb) {
                    let buffers = [];
                    for (let channel = 0; channel < numChannels; channel++) {
                        buffers.push(mergeBuffers(recBuffers[channel], recLength) as never);
                    }
                    let interleaved;
                    if (numChannels === 2) {
                        interleaved = interleave(buffers[0], buffers[1]);
                    } else {
                        interleaved = buffers[0];
                    }
                    let dataview = encodeWAV(interleaved);
                    let audioBlob = new Blob([dataview], {type});

                    if (_.isFunction(cb)) {
                        cb(audioBlob);
                    }
                },
                getBuffer(cb) {
                    let buffers = [];
                    for (let channel = 0; channel < numChannels; channel++) {
                        buffers.push(mergeBuffers(recBuffers[channel], recLength) as never);
                    }
                    if (_.isFunction(cb)) {
                        cb(buffers);
                    }
                },
                clear() {
                    recLength = 0;
                    recBuffers = [];
                    initBuffers();
                }
            };

            function initBuffers() {
                for (let channel = 0; channel < numChannels; channel++) {
                    recBuffers[channel] = [];
                }
            }

            function mergeBuffers(recBuffers, recLength) {
                let result = new Float32Array(recLength);
                let offset = 0;
                for (let i = 0; i < recBuffers.length; i++) {
                    result.set(recBuffers[i], offset);
                    offset += recBuffers[i].length;
                }
                return result;
            }

            function interleave(inputL, inputR) {
                let length = inputL.length + inputR.length;
                let result = new Float32Array(length);

                let index = 0;
                let inputIndex = 0;

                while (index < length) {
                    result[index++] = inputL[inputIndex];
                    result[index++] = inputR[inputIndex];
                    inputIndex++;
                }
                return result;
            }

            function floatTo16BitPCM(output, offset, input) {
                for (let i = 0; i < input.length; i++, offset += 2) {
                    let s = Math.max(-1, Math.min(1, input[i]));
                    output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
                }
            }

            //added for single channel
            function floatTo8BitPCM(output, offset, input) {
                for (let i = 0; i < input.length; i++, offset++) {
                    let s = Math.max(-1, Math.min(1, input[i]));
                    let val = s < 0 ? s * 0x8000 : s * 0x7fff;
                    val = parseInt((255 / (65535 / (val + 32768))) as any);
                    output.setInt8(offset, val, true);
                }
            }

            function writeString(view, offset, string) {
                for (let i = 0; i < string.length; i++) {
                    view.setUint8(offset + i, string.charCodeAt(i));
                }
            }

            function encodeWAV(samples) {
                let is2Channel = numChannels === 2;
                let sampleBits = is2Channel ? 16 : 8;
                let sampleBytes = sampleBits / 8;
                let dataLength = samples.length * sampleBytes;
                let buffer = new ArrayBuffer(44 + samples.length * sampleBytes);
                let view = new DataView(buffer);

                /* RIFF identifier */
                writeString(view, 0, 'RIFF');
                /* RIFF chunk length */
                view.setUint32(4, 36 + dataLength, true);
                /* RIFF type */
                writeString(view, 8, 'WAVE');
                /* format chunk identifier */
                writeString(view, 12, 'fmt ');
                /* format chunk length */
                view.setUint32(16, 16, true);
                /* sample format (raw) */
                view.setUint16(20, 1, true);
                /* channel count */
                view.setUint16(22, numChannels, true);
                /* sample rate */
                view.setUint32(24, sampleRate, true);
                /* byte rate (sample rate * block align) */
                view.setUint32(28, sampleRate * numChannels * sampleBytes, true);
                /* block align (channel count * bytes per sample) */
                view.setUint16(32, numChannels * sampleBytes, true);
                /* bits per sample */
                view.setUint16(34, sampleBits, true);
                /* data chunk identifier */
                writeString(view, 36, 'data');
                /* data chunk length */
                view.setUint32(40, dataLength, true);

                if (is2Channel) {
                    floatTo16BitPCM(view, 44, samples);
                } else {
                    floatTo8BitPCM(view, 44, samples);
                }

                return view;
            }
        })();

        this.worker.init({
            sampleRate,
            numChannels: this.config.numChannels
        });
    }

    onaudioprocess(e) {
        if (!this.recording) {
            return;
        }
        let buffer = [];
        for (let channel = 0; channel < this.config.numChannels; channel++) {
            //should clone the samples instead of directly pushing them!!!
            buffer.push(new Float32Array(e.inputBuffer.getChannelData(channel)) as never);
        }
        this.worker.record(buffer);
    }

    record() {
        this.recording = true;
    }

    stop() {
        this.recording = false;
    }

    clear() {
        this.worker.clear();
    }

    getBuffer(cb) {
        cb = cb || this.config.callback;
        if (!cb) {
            throw new Error('Callback not set');
        }

        this.worker.getBuffer(cb);
    }

    exportWAV(cb, mimeType) {
        mimeType = mimeType || this.config.mimeType;
        cb = cb || this.config.callback;
        if (!cb) {
            throw new Error('Callback not set');
        }
        this.worker.exportWAV(mimeType, cb);
    }

    static forceDownload(blob, filename) {
        let url = (window.URL || window['webkitURL']).createObjectURL(blob);
        let link = window.document.createElement('a');
        link.href = url;
        link.download = filename || 'output.wav';
        let click = document.createEvent('Event');
        click.initEvent('click', true, true);
        link.dispatchEvent(click);
    }
}

export function getRecorderInputVolume(analyser, volume, reset, tweenIn = 1.618, tweenOut = 0) {
    tweenOut = tweenOut || tweenIn * 3;
    let buffer = new Uint8Array(analyser.fftSize);
    analyser.getByteTimeDomainData(buffer);

    let range = getDynamicRange(buffer) * (Math.E - 1);
    let currentVolume = Math.floor(Math.log1p(range) * 100);
    let tween = currentVolume > volume ? tweenIn : tweenOut;
    currentVolume = reset ? currentVolume : volume + (currentVolume - volume) / tween;
    return currentVolume;
}

function getDynamicRange(buffer) {
    let len = buffer.length;
    let min = 128;
    let max = 128;

    for (let i = 0; i < len; i++) {
        let sample = buffer[i];
        if (sample < min) {
            min = sample;
        } else if (sample > max) {
            max = sample;
        }
    }

    return (max - min) / 255;
}
