"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Audio", {
    enumerable: true,
    get: function() {
        return Audio;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _object_spread_props = require("@swc/helpers/_/_object_spread_props");
var _object_without_properties = require("@swc/helpers/_/_object_without_properties");
var _sliced_to_array = require("@swc/helpers/_/_sliced_to_array");
var _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
var _taro = require("@tarojs/taro");
var _iconsreacttaro = require("@nutui/icons-react-taro");
var _components = require("@tarojs/components");
var _index = /*#__PURE__*/ _interop_require_default._(require("../range/index"));
var _index1 = /*#__PURE__*/ _interop_require_default._(require("../button/index"));
var _index2 = require("../configprovider/index");
var _typings = require("../../utils/typings");
var defaultProps = (0, _object_spread_props._)((0, _object_spread._)({}, _typings.ComponentDefaults), {
    className: '',
    src: '',
    style: {},
    autoplay: false,
    loop: false,
    type: 'progress',
    onFastBack: function onFastBack(ctx) {},
    onForward: function onForward(ctx) {},
    onPause: function onPause(ctx) {},
    onPlay: function onPlay(ctx) {},
    onPlayEnd: function onPlayEnd(ctx) {},
    onCanPlay: function onCanPlay(ctx) {}
});
var Audio = function Audio(props) {
    var formatSeconds = function formatSeconds(value) {
        if (!value) {
            return '00:00:00';
        }
        var time = parseInt(value);
        var hours = Math.floor(time / 3600);
        var minutes = Math.floor((time - hours * 3600) / 60);
        var secondss = time - hours * 3600 - minutes * 60;
        var result = '';
        result += "".concat("0".concat(hours.toString()).slice(-2), ":");
        result += "".concat("0".concat(minutes.toString()).slice(-2), ":");
        result += "0".concat(secondss.toString()).slice(-2);
        return result;
    };
    var classPrefix = 'nut-audio';
    var locale = (0, _index2.useConfig)().locale;
    var _ref = (0, _object_spread._)({}, defaultProps, props), className = _ref.className, src = _ref.src, style = _ref.style, autoplay = _ref.autoplay, loop = _ref.loop, type = _ref.type, onFastBack = _ref.onFastBack, onForward = _ref.onForward, onPause = _ref.onPause, onPlay = _ref.onPlay, onPlayEnd = _ref.onPlayEnd, onCanPlay = _ref.onCanPlay, children = _ref.children, iconClassPrefix = _ref.iconClassPrefix, iconFontClassName = _ref.iconFontClassName, rest = (0, _object_without_properties._)(_ref, [
        "className",
        "src",
        "style",
        "autoplay",
        "loop",
        "type",
        "onFastBack",
        "onForward",
        "onPause",
        "onPlay",
        "onPlayEnd",
        "onCanPlay",
        "children",
        "iconClassPrefix",
        "iconFontClassName"
    ]);
    var _useState = (0, _sliced_to_array._)((0, _react.useState)(false), 2), playing = _useState[0], setPlaying = _useState[1];
    var _useState1 = (0, _sliced_to_array._)((0, _react.useState)(0), 2), totalSeconds = _useState1[0], setTotalSeconds = _useState1[1];
    var _useState2 = (0, _sliced_to_array._)((0, _react.useState)(0), 2), percent = _useState2[0], setPercent = _useState2[1];
    var _useState3 = (0, _sliced_to_array._)((0, _react.useState)(false), 2), isCanPlay = _useState3[0], setIsCanPlay = _useState3[1];
    var _useState4 = (0, _sliced_to_array._)((0, _react.useState)('00:00:00'), 2), currentDuration = _useState4[0], setCurrentDuration = _useState4[1];
    var statusRef = (0, _react.useRef)({
        currentTime: 0,
        currentDuration: '00:00:00',
        percent: 0
    });
    var audioRef = (0, _react.useRef)((0, _taro.createInnerAudioContext)());
    var audioCtx = audioRef.current;
    audioCtx.src = src;
    audioCtx.autoplay = autoplay || false;
    audioCtx.loop = loop || false;
    audioCtx.onPause(function() {
        onPause === null || onPause === void 0 ? void 0 : onPause(audioCtx);
    });
    audioCtx.onEnded(function() {
        if (loop) {
            console.warn(locale.audio.tips || 'onPlayEnd事件在loop=false时才会触发');
        } else {
            onPlayEnd === null || onPlayEnd === void 0 ? void 0 : onPlayEnd(audioCtx);
        }
    });
    audioCtx.onPlay(function() {
        var duration = audioCtx.duration;
        setTotalSeconds(Math.floor(duration));
        onPlay === null || onPlay === void 0 ? void 0 : onPlay(audioCtx);
    });
    audioCtx.onCanplay(function() {
        var intervalID = setInterval(function() {
            if (audioCtx.duration !== 0) {
                setTotalSeconds(audioCtx.duration);
                clearInterval(intervalID);
            }
        }, 500);
        setIsCanPlay(true);
        onCanPlay === null || onCanPlay === void 0 ? void 0 : onCanPlay(audioCtx);
    });
    audioCtx.onTimeUpdate(function() {
        var time = parseInt("".concat(audioCtx.currentTime));
        var formated = formatSeconds("".concat(time));
        statusRef.current.currentDuration = formated;
        setPercent(time / totalSeconds * 100);
        setCurrentDuration(formatSeconds(audioCtx.currentTime.toString()));
    });
    audioCtx.onError(function(res) {
        console.warn('onError', res.errCode, res.errMsg);
    });
    var handleBack = function handleBack() {
        var currentTime = Math.floor(audioCtx.currentTime);
        statusRef.current.currentTime = Math.max(currentTime - 1, 0);
        setCurrentDuration(formatSeconds(statusRef.current.currentTime.toString()));
        audioCtx.seek(statusRef.current.currentTime);
        onFastBack === null || onFastBack === void 0 ? void 0 : onFastBack(audioCtx);
    };
    var handleForward = function handleForward() {
        var currentTime = Math.floor(audioCtx.currentTime);
        statusRef.current.currentTime = Math.min(currentTime + 1, audioCtx.duration);
        setCurrentDuration(formatSeconds(statusRef.current.currentTime.toString()));
        audioCtx.seek(statusRef.current.currentTime);
        onForward === null || onForward === void 0 ? void 0 : onForward(audioCtx);
    };
    var handleStatusChange = function handleStatusChange() {
        setPlaying(!playing);
        if (!playing) {
            audioCtx.play();
        } else {
            audioCtx.pause();
        }
    };
    var renderIcon = function renderIcon() {
        return /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(classPrefix, "-icon")
        }, /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(classPrefix, "-icon-box} ").concat(playing ? "".concat(classPrefix, "-icon-play}") : "".concat(classPrefix, "-icon-stop}")),
            onClick: handleStatusChange
        }, /*#__PURE__*/ _react.default.createElement(_iconsreacttaro.Service, {
            className: playing ? 'nut-icon-loading' : ''
        })));
    };
    var renderProgerss = function renderProgerss() {
        return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(classPrefix, "-progress")
        }, /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "time"
        }, currentDuration), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(classPrefix, "-progress-bar-wrapper")
        }, /*#__PURE__*/ _react.default.createElement(_index.default, {
            value: percent,
            onChange: function onChange(val) {
                return setPercent(val);
            },
            currentDescription: null,
            maxDescription: null,
            minDescription: null,
            "inactive-color": "var(--nutui-color-text-disabled, #c2c4cc)",
            "active-color": "var(--nutui-color-primary, #ff0f23)"
        })), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "time"
        }, formatSeconds("".concat(totalSeconds)) || '00:00:00')), /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: isCanPlay ? 'custom-button-group' : 'custom-button-group-disable'
        }, /*#__PURE__*/ _react.default.createElement(_index1.default, {
            type: "primary",
            size: "small",
            className: "back",
            onClick: handleBack
        }, locale.audio.back || '快退'), /*#__PURE__*/ _react.default.createElement(_index1.default, {
            type: "primary",
            size: "small",
            className: "start",
            onClick: handleStatusChange
        }, playing ? "".concat(locale.audio.pause || '暂停') : "".concat(locale.audio.start || '开始')), /*#__PURE__*/ _react.default.createElement(_index1.default, {
            type: "primary",
            size: "small",
            onClick: handleForward
        }, locale.audio.forward || '快进')));
    };
    var renderNone = function renderNone() {
        return /*#__PURE__*/ _react.default.createElement(_components.View, {
            className: "".concat(classPrefix, "-none-container"),
            onClick: handleStatusChange
        }, children);
    };
    var renderAudio = function renderAudio() {
        switch(type){
            case 'icon':
                return renderIcon();
            case 'progress':
                return renderProgerss();
            case 'none':
                return renderNone();
            default:
                return null;
        }
    };
    return /*#__PURE__*/ _react.default.createElement(_components.View, (0, _object_spread._)({
        className: "".concat(classPrefix, " ").concat(className),
        style: style
    }, rest), renderAudio());
};
Audio.displayName = 'NutAudio';
