/*
 * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
 * This file is part of Pydio.
 *
 * Pydio is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Pydio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Pydio.  If not, see <http://www.gnu.org/licenses/>.
 *
 * The latest code can be found at <https://pydio.com>.
 */

'use strict';

Object.defineProperty(exports, '__esModule', {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _observer = require('./observer');

var _observer2 = _interopRequireDefault(_observer);

var _soundmanager2 = require('soundmanager2');

// import { threeSixtyPlayer } from '../../../sm/360-player/script/360player';

var self = undefined,
    pl = undefined,
    sm = _soundmanager2.soundManager,
    // soundManager instance
uA = navigator.userAgent,
    isIE = uA.match(/msie/i),
    isOpera = uA.match(/opera/i),
    isSafari = uA.match(/safari/i),
    isChrome = uA.match(/chrome/i),
    isFirefox = uA.match(/firefox/i),
    isTouchDevice = uA.match(/ipad|iphone/i),
    hasRealCanvas = typeof window.G_vmlCanvasManager === 'undefined' && typeof document.createElement('canvas').getContext('2d') !== 'undefined',

// I dunno what Opera doesn't like about this. I'm probably doing it wrong.
fullCircle = isOpera || isChrome ? 359.9 : 360;

var STATUS_DEFAULT = "STATUS_DEFAULT";
var STATUS_BUFFERING = "STATUS_BUFFERING";
var STATUS_PLAYING = "STATUS_PLAYING";
var STATUS_PAUSED = "STATUS_PAUSED";

var css = {
    STATUS_DEFAULT: 'sm2_link',
    STATUS_BUFFERING: 'sm2_buffering',
    STATUS_PLAYING: 'sm2_playing',
    STATUS_PAUSED: 'sm2_paused'
};

var soundObserver = new _observer2['default']();

_soundmanager2.soundManager.setup({
    // path to directory containing SM2 SWF
    url: 'plugins/editor.soundmanager/sm/swf/'
});

var Player = (function (_React$Component) {
    _inherits(Player, _React$Component);

    function Player(props) {
        _classCallCheck(this, Player);

        _get(Object.getPrototypeOf(Player.prototype), 'constructor', this).call(this, props);

        this.state = {
            status: STATUS_DEFAULT
        };
    }

    _createClass(Player, [{
        key: 'componentDidMount',
        value: function componentDidMount() {
            var _this = this;

            var _props = this.props;
            var id = _props.id;
            var url = _props.url;
            var style = _props.style;
            var rich = _props.rich;
            var autoPlay = _props.autoPlay;
            var onFinish = _props.onFinish;

            _soundmanager2.soundManager.onready(function () {
                var sound = _soundmanager2.soundManager.getSoundById(id);

                // First we check if it already exists
                if (sound) {
                    return;
                }

                _soundmanager2.soundManager.createSound({
                    id: id,
                    url: url,
                    multiShot: false,
                    onplay: function onplay() {
                        return soundObserver.play(id);
                    },
                    onstop: function onstop() {
                        return soundObserver.stop(id);
                    },
                    onpause: function onpause() {
                        return soundObserver.pause(id);
                    },
                    onresume: function onresume() {
                        return soundObserver.resume(id);
                    },
                    onfinish: function onfinish() {
                        return soundObserver.finish(id);
                    },
                    onbufferchange: function onbufferchange() {
                        return soundObserver.bufferchange(id);
                    },
                    whileloading: function whileloading() {
                        return soundObserver.whileloading(id);
                    },
                    whileplaying: function whileplaying() {
                        return soundObserver.whileplaying(id);
                    }
                });

                if (!_this.props.disableAutoPlay) {
                    // Adding autoplay, listening to previous sound finish events
                    var previousSoundID = _soundmanager2.soundManager.soundIDs.indexOf(id) - 1;
                    if (previousSoundID > -1) {
                        soundObserver.observe("soundfinish" + _soundmanager2.soundManager.soundIDs[previousSoundID], function () {
                            _soundmanager2.soundManager.getSoundById(id).play();
                        });
                    }
                }
            });

            var oCanvasCTX = this.canvas.getContext('2d');

            oCanvasCTX.translate(parseInt(style.width / 2), parseInt(style.height / 2));
            oCanvasCTX.rotate(deg2rad(-90));

            soundObserver.observe("soundplay" + id, function () {
                _this.setState({ status: STATUS_PLAYING });
                if (_this.props.onPlay) _this.props.onPlay();
            });
            soundObserver.observe("soundpause" + id, function () {
                _this.setState({ status: STATUS_PAUSED });
                if (_this.props.onPause) _this.props.onPause();
            });
            soundObserver.observe("soundbuffering" + id, function () {
                _this.setState({ status: STATUS_BUFFERING });
            });
            soundObserver.observe("soundresume" + id, function () {
                _this.setState({ status: STATUS_PLAYING });
                if (_this.props.onPlay) _this.props.onPlay();
            });
            soundObserver.observe("soundstop" + id, function () {
                clearCanvas(_this.canvas);
                _this.setState({ status: STATUS_DEFAULT });
            });
            soundObserver.observe("soundfinish" + id, function () {
                clearCanvas(_this.canvas);
                _this.setState({ status: STATUS_DEFAULT });

                if (typeof onFinish === "function") {
                    onFinish();
                }
            });

            soundObserver.observe("soundwhileplaying" + id, function () {
                var sound = _soundmanager2.soundManager.getSoundById(id);
                var radius = rich ? 60 : 20;
                var width = rich ? 20 : 5;

                var durationEstimate = sound.durationEstimate > 0 ? sound.durationEstimate : sound.buffered[0].end;

                if (_this.canvas) {
                    // Background
                    drawSolidArc(_this.canvas, '#dddddd', radius, width, deg2rad(fullCircle), 0, false);
                    // Loading ring
                    drawSolidArc(_this.canvas, '#cccccc', radius, width, deg2rad(fullCircle * (sound.bytesLoaded / sound.bytesTotal)), 0, true);
                    // Playing ring
                    drawSolidArc(_this.canvas, '#000000', radius, width, deg2rad(fullCircle * (sound.position / durationEstimate)), 0, true);
                }

                _this.setState({
                    time: getTime(sound.position, true)
                });
            });

            // Making sure the status is correct if sound is already playing
            var sound = _soundmanager2.soundManager.getSoundById(id);
            if (sound && sound.playState === 1) {
                if (sound.paused) {
                    this.setState({
                        status: STATUS_PAUSED
                    });
                } else {
                    this.setState({
                        status: STATUS_PLAYING
                    });
                }
            }
        }
    }, {
        key: '_handleEvent',
        value: function _handleEvent(e) {
            var _props2 = this.props;
            var id = _props2.id;
            var rich = _props2.rich;

            var offset = rich ? 20 : 5;
            var sound = _soundmanager2.soundManager.getSoundById(id);
            var coords = getMouseXY(e);
            var x = coords[0];
            var y = coords[1];

            var rect = this.canvas.getBoundingClientRect();

            var canvasMidX = rect.left + parseInt(this.canvas.width / 2);
            var canvasMidY = rect.top + parseInt(this.canvas.height / 2);

            var deltaX = x - canvasMidX;
            var deltaY = y - canvasMidY;

            if (Math.abs(deltaX) < offset && Math.abs(deltaY) < offset) {
                if (e.type == "mouseup") {
                    _soundmanager2.soundManager.soundIDs.map(function (soundID) {
                        try {
                            soundID !== id && _soundmanager2.soundManager.sounds[soundID].stop();
                        } catch (e) {}
                    });
                    sound.togglePause();
                }
                return;
            }

            var angle = Math.floor(fullCircle - (rad2deg(Math.atan2(deltaX, deltaY)) + 180));

            var durationEstimate = sound.durationEstimate > 0 ? sound.durationEstimate : sound.buffered[0].end;
            var position = Math.floor(durationEstimate * (angle / fullCircle) / 1000);

            sound.setPosition(position * 1000);
            sound.resume();
        }
    }, {
        key: 'handleMouseUp',
        value: function handleMouseUp(e) {
            e.preventDefault();
            e.stopPropagation();

            this.dragging = false;

            this._handleEvent(e);

            return false;
        }
    }, {
        key: 'handleMouseMove',
        value: function handleMouseMove(e) {
            e.preventDefault();
            e.stopPropagation();

            if (this.dragging) {
                this._handleEvent(e);
            }

            return false;
        }
    }, {
        key: 'handleMouseDown',
        value: function handleMouseDown(e) {
            e.preventDefault();
            e.stopPropagation();

            this.dragging = true;

            this._handleEvent(e);

            return false;
        }
    }, {
        key: 'render',
        value: function render() {
            var _this2 = this;

            var _state = this.state;
            var status = _state.status;
            var time = _state.time;

            var className = "ui360";
            if (this.props.rich) {
                className += " ui360-vis";
            }

            var style = _extends({}, this.props.style, {
                "backgroundImage": "none"
            });

            var canvasStyle = {
                "width": this.props.style.width,
                "height": this.props.style.height,
                "backgroundColor": "transparent",
                "borderRadius": 0,
                "boxShadow": "none"
            };

            var childStyle = {
                "width": this.props.style.width,
                "height": this.props.style.height,
                "backgroundColor": "transparent",
                "border": 0,
                "borderRadius": 0,
                "boxShadow": "none"
            };

            var btnStyle = {
                "width": this.props.style.width,
                "height": this.props.style.height,
                "lineHeight": this.props.style.width + "px",
                "margin": 0,
                "top": 0,
                "left": 0,
                "bottom": 0,
                "right": 0
            };

            var timingStyle = {
                "width": this.props.style.width,
                "height": this.props.style.height,
                "lineHeight": this.props.style.height + "px"
            };

            var coverStyle = {
                "width": this.props.style.width,
                "height": this.props.style.height,
                "lineHeight": this.props.style.height + "px"
            };

            //

            return _react2['default'].createElement(
                'div',
                { className: 'sm2-inline-list', style: style },
                _react2['default'].createElement(
                    'div',
                    { className: className, style: style, onMouseMove: function (e) {
                            return _this2.handleMouseMove(e);
                        }, onMouseUp: function (e) {
                            return _this2.handleMouseUp(e);
                        }, onMouseDown: function (e) {
                            return _this2.handleMouseDown(e);
                        } },
                    _react2['default'].createElement(
                        'div',
                        { className: "sm2-360ui " + css[status], style: childStyle },
                        _react2['default'].createElement('canvas', { ref: function (el) {
                                return _this2.canvas = el;
                            }, className: 'sm2-canvas', style: canvasStyle, width: this.props.style.width, height: this.props.style.height }),
                        _react2['default'].createElement('span', { className: 'sm2-360btn sm2-360btn-default', style: btnStyle }),
                        _react2['default'].createElement(
                            'div',
                            { className: 'sm2-timing', style: timingStyle },
                            time
                        ),
                        _react2['default'].createElement('div', { className: 'sm2-cover', style: coverStyle })
                    )
                )
            );
        }
    }]);

    return Player;
})(_react2['default'].Component);

Player.propTypes = {
    // threeSixtyPlayer: React.PropTypes.object,
    autoPlay: _react2['default'].PropTypes.bool,
    rich: _react2['default'].PropTypes.bool.isRequired,
    onReady: _react2['default'].PropTypes.func
};

Player.defaultProps = {
    autoPlay: false,
    rich: true
};

var deg2rad = function deg2rad(nDeg) {
    return nDeg * Math.PI / 180;
};

var rad2deg = function rad2deg(nRad) {
    return nRad * 180 / Math.PI;
};

var getTime = function getTime(nMSec, bAsString) {

    // convert milliseconds to mm:ss, return as object literal or string
    var nSec = Math.floor(nMSec / 1000),
        min = Math.floor(nSec / 60),
        sec = nSec - min * 60;
    // if (min === 0 && sec === 0) return null; // return 0:00 as null
    return bAsString ? min + ':' + (sec < 10 ? '0' + sec : sec) : { 'min': min, 'sec': sec };
};

var getArcEndpointCoords = function getArcEndpointCoords(radius, radians) {

    return {
        x: radius * Math.cos(radians),
        y: radius * Math.sin(radians)
    };
};

var clearCanvas = function clearCanvas(oCanvas) {

    var canvas = oCanvas,
        ctx = null,
        width,
        height;
    if (canvas && canvas.getContext) {
        // use getContext to use the canvas for drawing
        ctx = canvas.getContext('2d');
    }
    width = canvas.offsetWidth;
    height = canvas.offsetHeight;
    ctx.clearRect(-(width / 2), -(height / 2), width, height);
};

var drawSolidArc = function drawSolidArc(oCanvas, color, radius, width, radians, startAngle, noClear) {

    var x = radius,
        y = radius,
        canvas = oCanvas,
        ctx,
        innerRadius,
        doesntLikeZero,
        endPoint;

    if (canvas && canvas.getContext) {
        // use getContext to use the canvas for drawing
        ctx = canvas.getContext('2d');
    }

    // re-assign canvas as the actual context
    oCanvas = ctx;

    if (!noClear) {
        clearCanvas(canvas);
    }
    // ctx.restore();

    if (color) {
        ctx.fillStyle = color;
    }

    oCanvas.beginPath();

    if (isNaN(radians)) {
        radians = 0;
    }

    innerRadius = radius - width;
    doesntLikeZero = isOpera || isSafari; // safari 4 doesn't actually seem to mind.

    if (!doesntLikeZero || doesntLikeZero && radius > 0) {
        oCanvas.arc(0, 0, radius, startAngle, radians, false);
        endPoint = getArcEndpointCoords(innerRadius, radians);
        oCanvas.lineTo(endPoint.x, endPoint.y);
        oCanvas.arc(0, 0, innerRadius, radians, startAngle, true);
        oCanvas.closePath();
        oCanvas.fill();
    }
};

var getMouseXY = function getMouseXY(e) {

    // http://www.quirksmode.org/js/events_properties.html
    e = e ? e : window.event;
    if (isTouchDevice && e.touches) {
        e = e.touches[0];
    }
    if (e.pageX || e.pageY) {
        return [e.pageX, e.pageY];
    } else if (e.clientX || e.clientY) {
        return [e.clientX + getScrollLeft(), e.clientY + getScrollTop()];
    }
};

var getScrollLeft = function getScrollLeft() {
    return document.body.scrollLeft + document.documentElement.scrollLeft;
};

var getScrollTop = function getScrollTop() {
    return document.body.scrollTop + document.documentElement.scrollTop;
};

exports['default'] = Player;
module.exports = exports['default'];
