/*
 * ページ・ロード時にTensorFlow.jsが読み込まれる。
 * バックエンドにはWebGPUかWebGLを使う。この他にwasm、cpuを使うこともできる。
 */
option = 'webgl';
if ('gpu' in navigator) {
    option = 'webgpu';
};
/*
 * TensorFlow.jsがReadyになったら、モデルを読み込む。
 */
tf.ready()
.then(() => {
    tf.setBackend(option).then(() => {
        apex.items.P1_STATUS.setValue("TensorFlow.js is Ready, Loading Model...");
        cocoSsd.load( { base: 'lite_mobilenet_v2' } ).then( (m) => {
            model = m; // modelはページ・グローバルな変数
            const selectedBackend = tf.getBackend();
            apex.items.P1_STATUS.setValue(`Model is Loaded - ${selectedBackend}`);
            /*
             * モデルが読み込めたら、Webcamのキャプチャを開始する。
             */
            navigator.mediaDevices.getUserMedia({ 
                audio: false,
                video: {
                    facingMode: false
                }
            })
            .then((stream) => {
                const currentStatus = apex.items.P1_STATUS.getValue();
                apex.items.P1_STATUS.setValue(`${currentStatus}, Webcam is ready`);
                const videoElement = document.getElementById("mystery");
                videoElement.srcObject = stream;
            })
            .catch((error) => {
                apex.items.P1_STATUS.setValue('Error accessing webcam');
                console.error('Error accessing webcam:', error);
            });
       });
    });
})
.catch((error) => {
    apex.items.P1_STATUS.setValue('Error loading model');
    console.error('Error loading model:', error);
});