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';
import ArrowRight from '@material-ui/icons/ArrowRight';

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

const videoJsOptions = {
    controls: true,
    width: '550',
    languages: {
        fr: {
          
            Replay: 'Jouer'
        }
      },
    autoplay:true,
    preload:"auto",
    playsinline : false,
    //videoEngine: 'webm-wasm',
    //liveui : true,
    fluid: true,
    nativeControlsForTouch:false,
    controlBar: {
        // hide fullscreen and volume controls
        fullscreenToggle: false,
        volumePanel: false,
        deviceButton: false,
        recordIndicator:true,
        recordToggle: false,
        PictureInPictureToggle:false,
        PlayToggle:false
    },
     poster: '/statique/images/webrtc/module-video-talents-tube.svg',
    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 => ({
        primary: {
            color: theme.palette.primary.main,
        },
        root: {
            position: 'relative',
            textAlign: 'center',
            paddingTop: theme.spacing(10),
            justifyContent: 'center',
        },
        button: {
            color: '#FFFFFF',
            padding: '9.6px 16px',
            borderColor: '#25D89A',
            border: '2px solid',
            margin:'15px 8px 25px 8px',
            textTransform: 'inherit',
            backgroundColor:'#25D89A',
        },
        buttonRelancer:{
            color: '#1E2327',
            borderColor: '#1E2327',
            border: '2px solid',
            margin: '15px 8px 25px 8px',
            padding: '9.6px 16px',
            textTransform: 'inherit',
            color: '#1E2327',
            borderColor: '#1E2327',

        },

        buttonArret: {
            color: '#FFFFFF',
            borderColor: '#FF5A5F',
            border: '2px solid',
            padding: '9.6px 16px',
            margin:'15px 8px 25px 8px',
            textTransform: 'inherit',
            backgroundColor:'#FF5A5F',
        },
        buttonLire: {
            color: '#FFFFFF',
            padding: '9.6px 16px',
            margin:'15px 8px 25px 8px',
            textTransform: 'inherit',
            backgroundColor:'#1689FB',
        },
        conteneurVideo:{
            width:'550px!important'
        },
        sendContainer: {
                         left: '-40px'
        },
    
      
    })

// const styles = theme => ({
//     root: {
//         margin: theme.spacing(1),
//         maxWidth: '400px', [theme.breakpoints.down('md')]: {
//             maxWidth: `${100 - (theme.spacing(1))}vw`
//         },
//         sendContainer: {
//             textAlign: 'center'
//         },
//         bouton: {
//             textTransform: 'inherit',
//             marginLeft: theme.spacing(1),
//             marginRight: theme.spacing(1),
//             padding: theme.spacing(1.2, 2),
//             color: theme.palette.secondary.main,
//             backgroundColor: theme.palette.primary.important,
//         },
//         conteneurVideo:{
//             width:'550px!important'
//         }
//     }
// })
class Recorder extends Component {

    state={
        canSend:false,
        isActiveLancer:true,
        isActiveArreter:false,
        isActiveLancerReplay:false,
        lancerText:"Démarrer l’enregistrement",
        lancerStyleRelance : 0,
    }

    handleLancer = (replay)=>{
        this.setState({
            isActiveLancer: !this.state.isActiveLancer,
            isActiveArreter: !this.state.isActiveArreter,
            lancerText : "Refaire une vidéo",
        })
        replay==1 ? this.setState({isActiveLancerReplay: 1}) : this.setState({isActiveLancerReplay: 0})  
        this.setState({lancerStyleRelance: 1})
    }


    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);
        });
        var vid= this.player;
        this.player.bigPlayButton.hide();


        // When you pass text in options it just creates a control text,
// which is displayed as tooltip when hovered on 
// this button viz the span in you div,
var myButton = this.player.controlBar.addChild("button");



// There are many functions available for button component 
// like below mentioned in this docs 
// https://docs.videojs.com/button. 
// You can set attributes and clasess as well.

// Getting html DOM
var myButtonDom = myButton.el();
//var myButtonDom2 = myButton2.el();
// Since now you have the html dom element 
// you can add click events


// Now I am setting the text as you needed.
// myButtonDom.innerHTML = "Youi";

myButtonDom.onclick = function(){
  //alert("Redirecting");
  vid.pause();
}  
   

        // device is ready
        this.player.on('deviceReady', () => {
            console.info('device is ready!');
            this.player.record().start();
            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);
    }

    recordPlayer = () => {
        // console.log('accessing recording: ', this.player.recordedData)
        if (this.player) {
            //this.player.recorder.start()
            this.player.ready();
            this.player.record().getDevice();
            this.handleLancer(0);   
        }
    }

    playPlayerAuto = () => {
        // console.log('accessing recording: ', this.player.recordedData)
        if (this.player) {
            //this.player.recorder.start()
            this.player.autoplay('play');
            
        }
    }
    pausePlayerAuto = () => {
        // console.log('accessing recording: ', this.player.recordedData)
        if (this.player) {
            //this.player.recorder.start()
            this.player.autoplay('pause');
            
        }
    }
    
     arretPlayer = () => {
        // console.log('accessing recording: ', this.player.recordedData)
        if (this.player) {
            this.player.record().stop();
            this.handleLancer(1);
        }
     }

    render() {
        const { classes, titreBouton } = this.props;
        let titreButtonLabel= "Choisir cette vidéo";
        

        if (titreBouton) {
            titreButtonLabel = titreBouton;        
            console.log("titre");
            console.log(titreButtonLabel);       
        }
        return (
            <div className={classes.conteneurVideo}>
                <div data-vjs-player>
                    <video id="myVideo" width='550' ref={node => this.videoNode = node} className="video-js vjs-default-skin" playsInline></video>
                </div>
                <div className={classes.sendContainer}>
                   
                    {this.state.isActiveLancer ? <Button className={this.state.lancerStyleRelance==1 ? classes.buttonRelancer: classes.button}   onClick={this.recordPlayer}>{this.state.lancerText}</Button> : null }
                    {this.state.isActiveArreter ?<Button className={classes.buttonArret}    onClick={this.arretPlayer}>Arrêter l'enregistrement</Button> : null }
                    {/* {this.state.isActiveLancerReplay ?<Button cyp="ButtonApply" variant="contained" className={classes.buttonLire}   onClick={this.playPlayerAuto}><ArrowRight className={ classes.InputKeyboardArrowRightIcon }/>Relire</Button>: null } */}
                    { this.state.canSend && <Button type="submit" className={classes.button}
                        className={classes.button}
                        onClick={this.sendBlob}>
                        {titreButtonLabel}
                    </Button>}
                </div>
                <div id="controleNav">
                    
                </div>
            </div>
        );
    }
}
export default withStyles(styles)(Recorder)
