"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const React = __importStar(require("react"));
const { useState, useEffect } = React;
const ImageArrayField_1 = require("./ImageArrayField");
const react_spinner_1 = __importDefault(require("react-spinner"));
const components_1 = require("../components");
const ReactContext_1 = __importDefault(require("../../ReactContext"));
const FILE_TYPES = ["audio/mp3", "audio/mpeg", "audio/x-wav", "audio/wav", "audio/wave", "audio/vnd.wave", "audio/flac", "audio/x-flac"];
let AudioArrayField = class AudioArrayField extends React.Component {
    constructor() {
        super(...arguments);
        this.ALLOWED_FILE_TYPES = FILE_TYPES;
        this.ACCEPT_FILE_TYPES = ["audio/*"];
        this.MAX_FILE_SIZE = 100 * 1024 * 1024;
        this.KEY = "AUDIO";
        this.ENDPOINT = "audio";
        this.GLYPH = "headphones";
        this.TRANSLATION_TAKE_NEW = "TakeNewRecording";
        this.TRANSLATION_SELECT_FILE = "SelectRecording";
        this.TRANSLATION_NO_MEDIA = "NoRecording";
        this.CONTAINER_CLASS = "audios-container";
        this.METADATA_FORM_ID = "MHL.63";
        this.renderMedia = (id, idx) => (React.createElement("div", { className: "audio-container" },
            React.createElement(AudioButton, { id: id, idx: idx, apiClient: this.props.formContext.apiClient, translations: this.props.formContext.translations }),
            React.createElement(components_1.GlyphButton, { className: "audio-metadata-button", variant: "info", glyph: "pencil", onClick: this.openModalFor(idx) },
                " ",
                this.props.formContext.translations.Edit)));
        this.renderLoadingMedia = () => null;
        this.renderLoadingMedia = () => React.createElement("div", { className: "audio-container loading" },
            React.createElement(react_spinner_1.default, null));
        this.onMediaClick = () => null;
        this.renderModalMedia = (idx) => (React.createElement("div", null,
            React.createElement("img", { src: this.state.modalMediaSrc }),
            React.createElement(LajiAudio, { id: this.props.formData[idx], style: { width: "100%" }, apiClient: this.props.formContext.apiClient, downloadLinks: true, translations: this.props.formContext.translations })));
        this.formatValue = (value) => {
            const { Glyphicon } = this.context.theme;
            return (value || []).map((id, idx) => React.createElement(Glyphicon, { key: idx, glyph: "headphones" }));
        };
    }
};
AudioArrayField.contextType = ReactContext_1.default;
AudioArrayField = __decorate([
    ImageArrayField_1.MediaArrayField
], AudioArrayField);
exports.default = AudioArrayField;
const AudioButton = React.forwardRef((props, ref) => {
    const [loaded, setLoaded] = useState(null);
    const [playing, setPlaying] = useState(null);
    const audioRef = React.useRef();
    const play = React.useCallback(() => {
        setPlaying(true);
        audioRef.current.play();
    }, [audioRef, setPlaying]);
    const stop = React.useCallback(() => {
        audioRef.current.pause();
        audioRef.current.currentTime = 0;
        setPlaying(false);
    }, [audioRef, setPlaying]);
    const onKeyDown = React.useCallback((e) => {
        if (e.key === " ") {
            playing ? stop() : play();
            e.preventDefault();
            e.stopPropagation();
        }
    }, [playing, stop, play]);
    const { Glyphicon } = React.useContext(ReactContext_1.default).theme;
    return (React.createElement(React.Fragment, null,
        !loaded
            ? React.createElement("div", { className: "media-loading" },
                React.createElement(react_spinner_1.default, null))
            : React.createElement(Glyphicon, { glyph: playing ? "pause" : "play", onClick: playing ? stop : play, ref: ref, tabIndex: 0, onKeyDown: onKeyDown }),
        React.createElement(LajiAudio, { style: { display: "none" }, ref: audioRef, id: props.id, onLoaded: setLoaded, onStop: stop, apiClient: props.apiClient, translations: props.translations })));
});
const LajiAudio = React.forwardRef((props, ref) => {
    const [mp3Url, setMp3Url] = useState(null);
    const [wavUrl, setWavUrl] = useState(null);
    const [flacUrl, setFlacUrl] = useState(null);
    useEffect(() => __awaiter(void 0, void 0, void 0, function* () {
        let response;
        try {
            response = yield props.apiClient.get(`/audio/${props.id}`);
            setMp3Url(response.mp3URL);
            setWavUrl(response.wavURL);
            setFlacUrl(response.flacURL);
        }
        catch (e) {
        }
        props.onLoaded && props.onLoaded(true);
    }));
    return !mp3Url ? React.createElement(react_spinner_1.default, { style: props.style }) : (React.createElement("div", null,
        React.createElement("audio", { controls: true, style: props.style, ref: ref, onPause: props.onStop },
            React.createElement("source", { src: mp3Url })),
        props.downloadLinks && (React.createElement(React.Fragment, null,
            React.createElement("a", { href: mp3Url, download: true }, `${props.translations.Download} mp3`),
            wavUrl &&
                React.createElement(React.Fragment, null,
                    " | ",
                    React.createElement("a", { href: wavUrl, download: true }, `${props.translations.Download} wav`)),
            flacUrl &&
                React.createElement(React.Fragment, null,
                    " | ",
                    React.createElement("a", { href: flacUrl, download: true }, `${props.translations.Download} flac`))))));
});
