import React, { Component } from 'react'
import videojs from 'video.js';
import dynamic from 'next/dynamic'
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core/styles'
import axios from 'axios'
import setAuthorizationHeader from "../../data/setAuthorizationHeader";
import 'videojs/dist/video-js.css';
import 'videojs-record/dist/css/videojs.record.css';

dynamic(() => import('webrtc-adapter'), {
    ssr: false
})
const RTCRecorder = dynamic(() => import('RecordRTC'), {
    ssr: false
})

const videoJsOptions = {
    controls: true,

    fluid: true,
    plugins: {
      /*
      // wavesurfer section is only needed when recording audio-only
      wavesurfer: {
          src: 'live',
          waveColor: '#36393b',
          progressColor: 'black',
          debug: true,
          cursorWidth: 1,
          msDisplayMax: 20,
          hideScrollbar: true
      },
      */
      record: {
        audio: true,
        video: true,
        maxLength: 600,
        //debug: true
      }
    }
  };

const styles = theme => ({
    root: {
        margin: theme.spacing(1),
        maxWidth: '400px', [theme.breakpoints.down('md')]: {
            maxWidth: `${100 - (theme.spacing(1))}vw`
        },
        sendContainer: {
            textAlign: 'center'
        },
        button: {
            textTransform: 'inherit',
            marginLeft: theme.spacing(8),
            marginRight: theme.spacing(8),
            marginTop: theme.spacing(4),
            marginBottom: theme.spacing(2),
            padding: theme.spacing(1.2, 2),
            //borderRadius: '3px',
            [theme.breakpoints.up('sm')]: {
                margin: 'auto',
            },

        },
    }
})
class Recorder extends Component {

    state={
        canSend:false
    }

    async componentDidMount() {
        var record = (await import('videojs-record')).default
        // instantiate Video.js
        this.player = videojs(this.videoNode, videoJsOptions, () => {
            // print version information at startup
            var version_info = 'Using video.js ' + videojs.VERSION +
                ' with videojs-record ' + videojs.getPluginVersion('record') +
                ' and recordrtc ' + RTCRecorder.VERSION;
            videojs.log(version_info);
        });

        // device is ready
        this.player.on('deviceReady', () => {
            console.info('device is ready!');
            this.setState({canSend:false});
        });

        // user clicked the record button and started recording
        this.player.on('startRecord', () => {
            console.log('started recording!');
            this.setState({canSend:false});
        });

        // user completed recording and stream is available
        this.player.on('finishRecord', () => {
            // recordedData is a blob object containing the recorded data that
            // can be downloaded by the user, stored on server etc.
            console.log('finished recording: ', this.player.recordedData);
            this.setState({canSend:true});
        });

        // error handling
        this.player.on('error', (element, error) => {
            console.warn(error);
            this.setState({canSend:false});
        });

        this.player.on('deviceError', () => {
            console.error('device error:', this.player.deviceErrorCode);
            this.setState({canSend:false});
        });
    }

    //destroy player on unmount
    componentWillUnmount() {
        if (this.player) {
            this.player.dispose();
        }
    }

    sendBlob = () => {
       // console.log('accessing recording: ', this.player.recordedData)
        var formData = new FormData();
        formData.append('upload', this.player.recordedData, "myupload");

        this.props.uploader(formData);
    }

    render() {
        const { classes, titreBouton } = this.props;
        let titreButtonLabel= "Envoyer";
        

        if (titreBouton) {
            titreButtonLabel = titreBouton;        
            console.log("titre");
            console.log(titreButtonLabel);       
        }
        return (
            <div>
                <div data-vjs-player>
                    <video id="myVideo" ref={node => this.videoNode = node} className="video-js vjs-default-skin" playsInline></video>
                </div>
                <div className={classes.sendContainer}>
                   { this.state.canSend && <Button type="submit" variant="outlined" color="primary"
                        className={classes.button}
                        onClick={this.sendBlob}>
                        {titreButtonLabel}
                    </Button>}
                </div>
            </div>
        );
    }
}
export default withStyles(styles)(Recorder)
