<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>โปรแกรมช่วยเตือนผู้ป่วยตกเตียง</title>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
    <link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@400;700&display=swap" rel="stylesheet">
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            height: 100vh;
            margin: 0;
            font-family: 'Sarabun', sans-serif;
            background: linear-gradient(to bottom, #a8e6a1, #d1f8d4);
            color: #333;
        }
        canvas {
            border: 2px solid #007BFF;
            border-radius: 8px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }
        #controls {
            margin-top: 20px;
            text-align: center;
        }
        button {
            background-color: #007BFF;
            color: #fff;
            border: none;
            border-radius: 5px;
            padding: 10px 15px;
            margin: 5px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:active {
            background-color: #003f7f;
        }
        #muteSound {
            margin-left: 10px;
            transform: scale(1.2);
            cursor: pointer;
        }
        label {
            font-weight: bold;
        }
        h1, h2 {
            text-align: center;
            margin: 0;
        }
        h1 {
            color: #007BFF;
            font-size: 24px;
            margin-bottom: 10px;
        }
        h2 {
            font-size: 18px;
            color: #555;
            margin-bottom: 20px;
        }
        video {
            display: none; /* ซ่อนวิดีโอ */
        }
        footer {
            position: absolute;
            bottom: 10px;
            right: 10px;
            font-size: 12px;
            color: #555;
        }
    </style>
</head>
<body>
    <h1>โปรแกรมช่วยเตือนผู้ป่วยตกเตียง</h1>
    <h2></h2>
    <video id="video" width="640" height="480" autoplay muted></video>
    <canvas id="canvas" width="640" height="480"></canvas>
    <div id="controls">
        <button id="increaseLine">ลดแนวเส้นเตือน</button>
        <button id="decreaseLine">เพิ่มแนวเส้นเตือน</button>
        <label for="muteSound">ปิดการแจ้งเตือน:</label>
        <input type="checkbox" id="muteSound" checked>
    </div>
    <footer>โดย นายนันทพล ทวิชสังข์ นักกายภาพบำบัดชำนาญการพิเศษ</footer>

    <script>
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const increaseLineButton = document.getElementById('increaseLine');
        const decreaseLineButton = document.getElementById('decreaseLine');
        const muteSoundCheckbox = document.getElementById('muteSound');

        let model;
        let bedLevel = 180; // ตั้งค่าตำแหน่งเส้นเริ่มต้นที่ 300
        let isAlarmPlaying = false;
        let alarmAudioContext = new (window.AudioContext || window.webkitAudioContext)();
        let oscillator = null;
        let gainNode = null;
		
        // ฟังก์ชันเล่นเสียง
        function playAlarm() {
            if (!isAlarmPlaying && !muteSoundCheckbox.checked) {
                oscillator = alarmAudioContext.createOscillator();
                gainNode = alarmAudioContext.createGain();

                oscillator.frequency.value = 1000; // ความถี่เสียง (1kHz)
                oscillator.type = 'square'; // รูปคลื่นสี่เหลี่ยม
                gainNode.gain.value = 1; // ความดัง
                oscillator.connect(gainNode);
                gainNode.connect(alarmAudioContext.destination);

                oscillator.start(); // เริ่มเสียง
                isAlarmPlaying = true; // ตั้งสถานะว่าเสียงกำลังเล่นอยู่
				document.body.style.background = 'linear-gradient(to bottom, #ff0000, #cc0000)';
            }
        }

        // ฟังก์ชันหยุดเสียง
        function stopAlarm() {
            if (isAlarmPlaying) {
                oscillator.stop(); // หยุดเสียง
                oscillator.disconnect();
                gainNode.disconnect();
                isAlarmPlaying = false; // ตั้งสถานะว่าเสียงหยุดแล้ว
				document.body.style.background = 'linear-gradient(to bottom, #a8e6a1, #d1f8d4)';
            }
        }

        // โหลดกล้อง
		async function setupCamera() {
		try {
        const stream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: { exact: "environment" } } // ใช้กล้องหลัง
        });
        video.srcObject = stream;
        return new Promise((resolve) => {
            video.onloadedmetadata = () => {
                resolve(video);
            };
        });
		} catch (err) {
			console.error('ไม่สามารถเข้าถึงกล้อง:', err);
		}
		}


        // วาดเส้นสีแดง
        function drawRedLine() {
            ctx.strokeStyle = 'red';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.moveTo(0, bedLevel);
            ctx.lineTo(canvas.width, bedLevel);
            ctx.stroke();
        }

        // ตรวจจับวัตถุและควบคุมเสียง
        async function detectObjects() {
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            drawRedLine();

            const predictions = await model.detect(video);
            let isAboveLine = false;

            predictions.forEach(prediction => {
                const [x, y, width, height] = prediction.bbox;
                const bottomY = y;

                // ตรวจสอบเฉพาะวัตถุที่เป็นคน
                if (prediction.class === 'person' && bottomY < bedLevel) {
                    isAboveLine = true;
                }

                // วาดกรอบและข้อความ
                ctx.strokeStyle = 'green';
                ctx.lineWidth = 2;
                ctx.strokeRect(x, y, width, height);
                ctx.fillStyle = 'green';
                ctx.font = '16px Arial';
                ctx.fillText(prediction.class, x, y - 5);
            });

            // เล่นเสียงเมื่อวัตถุอยู่เหนือเส้นแดง
            if (isAboveLine) {
                playAlarm();
            } else {
                stopAlarm();
            }

            requestAnimationFrame(detectObjects);
        }

        // เริ่มต้นโปรแกรม
        async function init() {
            await setupCamera();
            video.play();

            model = await cocoSsd.load();

            detectObjects();
        }

        // ปุ่มเพิ่มเส้น
        increaseLineButton.addEventListener('click', () => {
            if (bedLevel < canvas.height) {
                bedLevel += 10; // เพิ่มตำแหน่งเส้นขึ้น 10 พิกเซล
            }
        });

        // ปุ่มลดเส้น
        decreaseLineButton.addEventListener('click', () => {
            if (bedLevel > 0) {
                bedLevel -= 10; // ลดตำแหน่งเส้นลง 10 พิกเซล
            }
        });

        // ตรวจสอบสถานะการ mute เสียง
        muteSoundCheckbox.addEventListener('change', () => {
            if (muteSoundCheckbox.checked) {
                stopAlarm(); // หยุดเสียงถ้า mute
            }
        });

        init();
    </script>
</body>
</html>
