import Recorder from 'recorder-js';

enum TriggerListener {
    fail='fail',
    end='end',
    success='success',
    speed='speed',
    status='status',
    soundStatus='soundStatus'
}

export {TriggerListener};

let recorder = undefined;

export default  class SoundRecording {

    triggers:Record<string, any>={};

    private recorder = recorder;

    // 创建配置
    constructor(public config:SoundRecordingConfig={}) {

        for (let key in SoundRecording.defaultConfig) {
            if (SoundRecording.defaultConfig.hasOwnProperty(key) && config[key] === undefined) {
                config[key] = SoundRecording.defaultConfig[key];
            }
        }

    }

    // 是否装载
    initializationStatus=false;

    // 获取录音权限
    initialization(){

        if (this.initializationStatus) return ;
        this.initializationStatus = true;

        return new Promise<void>( (resolve, reject)=>{

            if (recorder) {
                this.recorder = recorder;
                resolve();
            } else {

                // @ts-ignore
                let getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

                if (getUserMedia) {
                    return navigator.mediaDevices.getUserMedia({audio: true}).then((stream)=>{
                        // @ts-ignore
                        const audioContext =  new (window.AudioContext || window.webkitAudioContext)();
                        this.recorder = new Recorder(audioContext,{
                            type:'audio/mp3'
                        });
                        this.recorder.init(stream);
                        resolve();
                    }).catch(()=> {
                        this.initializationStatus = false;
                        reject({ jurisdiction:false })
                    });
                } else {
                    this.initializationStatus = false;
                    reject({
                        support:false
                    });
                }

            }



        });

    }

    // 录音
    start(){

        if (!this.recorder || this.config.status) return;

        // 设置状态为开始录音
        this.setStatus(true);

        this.recorder.start().then(()=>{

            this.config.countdown = 0;

            this.config.startTime = this.getDate();

            this.triggerListener(TriggerListener.soundStatus,true);

            return this.triggerStart();

        }).catch(()=>{
            // 结束录音模式
            this.setStatus(false);
            // 错误
            return this.triggerListener(TriggerListener.fail,'无法启用录音');
        });

    }

    // 结束录音
    stop(){
        if (!this.recorder || !this.config.status) return;

        clearTimeout(this.config.time);

        this.recorder.stop().then((data)=>{
            // 结束录音模式
            this.setStatus(false);
            if (this.config.countdown >= this.config.min) {
                this.triggerListener(TriggerListener.soundStatus,false);
                return this.triggerListener(TriggerListener.success,data);
            } else {
                return this.triggerListener(TriggerListener.fail,'录音时间不能小于'+this.config.min+'s');
            }
        }).catch(()=>{
            // 结束录音模式
            this.setStatus(false);
            // 错误
            return this.triggerListener(TriggerListener.fail,'无法启用录音');
        });

    }

    // 开始录音计时器
    triggerStart(){

        if (!this.config.startTime) return;

        this.config.countdown = this.getDate() - this.config.startTime;

        this.triggerListener(TriggerListener.speed,this.config.countdown);

        if (this.config.countdown > this.config.max) {
            clearTimeout(this.config.time);
            return this.stop();
        } else {
            this.config.time = setTimeout(()=> this.triggerStart(),1000);
        }

    }

    // 获取时间
    getDate(){
        return Math.floor(new Date().getTime()/1000);
    }

    // 设置状态
    setStatus(status:boolean){
        if (this.config.status !== status) {
            this.config.status = status;
            this.triggerListener(TriggerListener.status,status);
        }
    }

    addListener(key:TriggerListener,callback:Function) {

        if (!callback) return;

        if (this.triggers[key] === undefined) this.triggers[key] = [callback];
        else this.triggers[key].push(callback);

        return this;

    }

    removeListener(key:TriggerListener,callback:Function) {

        if (!callback || this.triggers[key] === undefined) return;

        let index = this.triggers[key].indexOf(callback);

        if (index>=0) this.triggers[key].splice(index,1);

        return this;

    }

    triggerListener(key:TriggerListener,data?:any) {

        if (this.triggers[key]) {
            this.triggers[key].map((item)=> item && item(data));
        }

    }

    // 默认的配置文件
    static defaultConfig:SoundRecordingConfig = {
        min:3,
        max:15,
        status:false
    }


}

console.log(Recorder);