// @flow
import React, { Component } from 'react';
import Peaks from '../../node_modules/peaks.js/peaks.js';
import Colors from './Colors';

class WaveformPeaks extends Component {
    props: {
       filePath: string,
       pos: number,
       handlePosChange: Function,
       playing: boolean
    };

    constructor(props) {
        super(props);

        this.ctx = new AudioContext();

        this.resolveAudioPromise = null;
        this.resolveContainerPromise = null;
        const promises = [
            new Promise((resolve, reject) => {
                this.resolveAudioPromise = resolve;
            }),
            new Promise((resolve, reject) => {
                this.resolveContainerPromise = resolve;
            })
        ];
        
        Promise.all(promises).then(this.initPeaks.bind(this));

        this.onAudio = this.onAudio.bind(this);
        this.onContainer = this.onContainer.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if(this.props.filePath !== nextProps.filePath) {
            console.log('destroy peaks')
            this.peaks.destroy();
            this.peaks = null;
            this.audio.src = nextProps.filePath;
            this.initPeaks();
        }
    }

    componentDidUpdate(prevProps, prevState) {
        console.log('componentDidUpdate')
        if(this.props.playing && !prevProps.playing) {
            this.audio.play();
        } else if(!this.props.playing && prevProps.playing) {
            this.audio.pause();
        }
        if(this.props.segments !== prevProps.segments) {
            console.log('segments changed')
            this.addSegments();
        }
    }

    addSegments() {
        const peaks = this.peaks;
        const { segments, fileName } = this.props;

        if(peaks.segments && peaks.segments.add && peaks.segments.removeAll) {
            // Need to optimize this
            peaks.segments.removeAll()
            segments.forEach(({ startTimeSeconds, endTimeSeconds, id }, index) => {
                peaks.segments.add({
                    startTime: startTimeSeconds, 
                    endTime: endTimeSeconds, 
                    color: Colors[index], 
                    labelText: `${fileName}_${index + 1}`,
                    id,
                    editable: true
                });
            });
        }
    }

    onAudio(audio) {
        console.log('save audio ref');
        this.audio = audio;
        this.audio.addEventListener('loadedmetadata', () => {
            console.log('audio loadedmetadata', audio.currentSrc);
            this.resolveAudioPromise();
        });
        this.audio.addEventListener('timeupdate', (e) => {
            //console.log('audio timeupdate', this.audio.currentTime);
            this.props.handlePosChange(this.audio.currentTime);
        });
    }

    onContainer(container) {
        console.log('save container ref');
        this.container = container;
        this.resolveContainerPromise();
    }

    initPeaks() {
        console.log('initPeaks');
        const container = this.container;
        const audio = this.audio;
        const ctx = this.ctx;

        this.peaks = Peaks.init({
            container: container,
            mediaElement: audio,
            audioContext: ctx,
            height: 150,
            zoomWaveformColor: 'rgba(0, 225, 128, 1)',
            playheadColor: '#D62B70'
        });

        this.peaks.on('error', (err) => {
            console.log('peaks had an error', err);
        });

        this.peaks.on('segments.ready', () => {
            console.log('peaks segments ready');
            this.addSegments();
        });

        this.peaks.on('user_seek.overview', (pos) => {
            console.log('user_seek.overview', pos);
        });

        this.peaks.on('user_seek.zoomview', (pos) => {
            console.log('user_seek.zoomview', pos);
        });
    }

    render() {
        
        const { filePath, pos, handlePosChange, playing } = this.props;
        console.log('render ', filePath)
        
        return (
            <div>
                <div id="peaks-container" ref={(container) => { !this.container && this.onContainer(container); }}></div>
                <audio ref={(audio) => { !this.audio && this.onAudio(audio); }}  src={filePath}>
                </audio>
            </div>
        );
    }
}

export default WaveformPeaks;
@@ -410,227 +410,58 @@
 olve
-AudioPromise = null;%0A        this.resolveContainerPromise = null;%0A        const promises = %5B%0A            new Promise((resolve, reject) =%3E %7B%0A                this.resolveAudioPromise = resolve;%0A            %7D),%0A           
+ContainerPromise = null;%0A%0A        this.container =
  new
@@ -496,36 +496,32 @@
 %3E %7B%0A            
-  
-  
 this.resolveCont
@@ -556,95 +556,9 @@
     
-    %7D)%0A        %5D;%0A        %0A        Promise.all(promises).then(this.initPeaks.bind(this)
+%7D
 );%0A%0A
@@ -685,107 +685,50 @@
 nent
-WillReceiveProps(nextProps) %7B%0A        if(this.props.filePath !== nextProps.filePath) %7B%0A    
+DidUpdate(prevProps, prevState) %7B%0A
         
 cons
@@ -715,32 +715,34 @@
 tate) %7B%0A        
+//
 console.log('des
@@ -742,88 +742,85 @@
 og('
-destroy peaks')%0A            this.peaks.destroy();%0A            this.peaks = null;
+componentDidUpdate')%0A        if(prevProps.filePath !== this.props.filePath) %7B
 %0A   
@@ -849,13 +849,14 @@
 c = 
-nextP
+this.p
 rops
@@ -878,135 +878,10 @@
     
-    this.initPeaks();%0A        %7D%0A    %7D%0A%0A    componentDidUpdate(prevProps, prevState) %7B%0A        console.log('componentDidUpdate')
+%7D%0A
 %0A   
@@ -1071,151 +1071,8 @@
   %7D%0A
-        if(this.props.segments !== prevProps.segments) %7B%0A            console.log('segments changed')%0A            this.addSegments();%0A        %7D%0A
     
@@ -2004,28 +2004,103 @@
 his.
-resolveAudioPromise(
+container.then((container) =%3E %7B%0A                this.initPeaks(container, audio);%0A            %7D
 );%0A 
@@ -2173,34 +2173,32 @@
 %3E %7B%0A            
-//
 console.log('aud
@@ -2406,28 +2406,40 @@
    this.
-container = 
+resolveContainerPromise(
 containe
@@ -2443,75 +2443,115 @@
 iner
+)
 ;%0A    
+%7D%0A%0A
     
-this.resolveContainerPromise(
+initPeaks(container, audio) %7B%0A        console.log('initPeaks'
 );%0A    
-%7D%0A%0A
     i
-nitP
+f(this.p
 eaks
-(
 ) %7B%0A
+    
     
@@ -2559,37 +2559,41 @@
    console.log('
-initP
+destroy p
 eaks');%0A        
@@ -2596,75 +2596,83 @@
     
-const container = this.container;%0A        const audio = this.audio;
+    this.peaks.destroy();%0A            this.peaks = null;%0A        %7D%0A        
 %0A   
@@ -3707,25 +3707,21 @@
 %7B !this.
-container
+peaks
  && this
@@ -3802,21 +3802,21 @@
 %7B !this.
-audio
+peaks
  && this

fix waveform not matching audio file