/*
NAME
  main.js

AUTHOR
  Trek Hopton <trek@ausocean.org>

LICENSE
  This file is Copyright (C) 2019 the Australian Ocean Lab (AusOcean)

  It is free software: you can redistribute it and/or modify them
  under the terms of the GNU General Public License as published by the
  Free Software Foundation, either version 3 of the License, or (at your
  option) any later version.

  It 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 General Public License
  for more details.

  You should have received a copy of the GNU General Public License in gpl.txt.
  If not, see http://www.gnu.org/licenses.
*/

// play will process and play the chosen target file.
function play() {
    const viewer = document.getElementById('viewer');
    const input = event.target.files[0];
    const reader = new FileReader();

    reader.onload = event => {
        const player = new Worker("player.js");

        let rate = document.getElementById('rate');
        if (rate.value && rate.value > 0) {
            player.postMessage({ msg: "setFrameRate", data: rate.value });
        }

        player.onmessage = e => {
            switch (e.data.msg) {
                case "frame":
                    const blob = new Blob([new Uint8Array(e.data.data)], {
                        type: 'video/x-motion-jpeg'
                    });
                    const url = URL.createObjectURL(blob);
                    viewer.src = url;
                    break;
                case "log":
                    console.log(e.data.data);
                    break;
                case "stop":
                    break;
                default:
                    console.error("unknown message from player");
                    break;
            }
        };

        switch (input.name.split('.')[1]) {
            case "mjpeg":
            case "mjpg":
                player.postMessage({ msg: "loadMjpeg", data: event.target.result }, [event.target.result]);
                break;
            case "ts":
                player.postMessage({ msg: "loadMtsMjpeg", data: event.target.result }, [event.target.result]);
                break;
            default:
                console.error("unknown file format");
                break;
        }
    };
    reader.onerror = error => reject(error);
    reader.readAsArrayBuffer(input);

}