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 CircularProgress from '@material-ui/core/CircularProgress';
import utils from '../src/utils'
import 'videojs/dist/video-js.css';
import 'videojs-record/dist/css/videojs.record.css';

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

//import RecordRTC from 'recordrtc';
const RTCRecorder = dynamic(() => import('RecordRTC'), {
    ssr: false
})


//import Record from 'videojs-record/dist/videojs.record';
// const record = dynamic(() => import('videojs-record/dist/videojs.record'), {
//         ssr: false
//       })

const styles = theme => ({
    root: {
        margin: theme.spacing.unit,
        maxWidth: '400px', [theme.breakpoints.down('md')]: {
            maxWidth: `${100 - (theme.spacing.unit)}vw`
        },
        button: {

            margin: theme.spacing.unit,
            alignSelf: 'flex-end'
        },
    }
})
class Recorder extends Component {

    async componentDidMount() {
        var record = (await import('videojs-record/dist/videojs.record.js')).default
        // instantiate Video.js
        this.player = videojs(this.videoNode, this.props, () => {
            // 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!');
        });

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

        // 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.info('finished recording: ', this.player.recordedData);
        });

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

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

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

    sendBlob = () => {
        console.info('accessing recording: ', this.player.recordedData)
        var formData = new FormData();
        formData.append('upload', this.player.recordedData, "myupload");
        //   formData.append('user', 7);//TODO: taking from auth

        utils.setAuthorizationHeader('eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE1NTk3Mzk1MjUsImV4cCI6MTU1OTc0MzEyNSwicm9sZXMiOlsiUk9MRV9UQUxFTlQiLCJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJ0aG9tYXMuYmVycm9kQGUtZGVjbGljLmNvbSJ9.iW5DwfZuF3Qpa4exqI5Q8t_kv22ZUA7pvs4sFc-Qgl6qRH516thDKg-h7b0A1590xM8wI4WnEXJgOu5IT64UCeVtJpXaa9AzwhSFjVAv0SwkVt73NoJ45NiyxQsx_41Xjk1NAGVOIHvGgcMOEiZj4n1qXJeskjRmU-yprZ8Atg9ce1P4BEsAth99DN0KMtEjrP3VW8SFh9kOOGB9IGLTq5FRRvdONStW0MRRtS3KSwFzOZsMRqStW8ncI1EaRt76ulEKkx-Ka4WkdTc--DR9v5N36negmCgh54U0YPZ9B9lsJXDTsHdDkqC4f6nY0Wm-TNKKK1E5fPL86lkkHkure8JgLKKbATaEk5CDdRJAQED1T_cDId4OgnCGrzSEUbpCg0hx1V8EY4Y2l_AQOFfTxfBobTJ5Yf4zdtVok84ww5QV3GQG9bfmbEWyR1RxegC6s0am9SSLSsuZ-UDSmv336sSIh38ldzivUdnN7YHD0_QihDgLOPtZEsiEjsmbFBgX3fwSsGI0cs7UtCSiwsFLjDm6vxIQU9GK54pa82x-3N-7njDF0BgRE4gUoLDfREZdApaWXGpvHAoQQd9Y1vsWDQxE3JQQKRGkqWex7YYo-98Jweax2DzJeeAvFQeGEzE_O4m1rVG832Z0IAkt8wYRnsGFMlCjLysHoL0xTFNWUqE')

        axios.post("http://localhost/app_dev.php/api/media",
            formData,
            {
                headers: {
                    'Content-Type': `multipart/form-data;`
                },
                withCredentials: true
            })
            .then(res => console.info(res)).catch(err => console.error(err))

        console.info('end send Blob')
    }

    render() {
        const { classes } = this.props;
        return (
            <div>
                <div data-vjs-player>
                    <video id="myVideo" ref={node => this.videoNode = node} className="video-js vjs-default-skin" playsInline></video>
                </div>
                <div>
                    <Button type="submit" variant="outlined" color="secondary"
                        className={classes.button}
                        onClick={this.sendBlob}>
                        Send
                </Button>
                </div>
            </div>
        );
    }
}
export default withStyles(styles)(Recorder)
