@extends('layouts.master')
@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        #canvas {
            border: 1px solid black;
        }

        /* Custom styles for the range input */
        input[type="range"] {
            -webkit-appearance: none;
            width: 100%;
            height: 8px;
            border-radius: 5px;
            background: #ddd;
            outline: none;
            opacity: 0.7;
            -webkit-transition: .2s;
            transition: opacity .2s;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #007bff;
            /* Bootstrap primary color */
            cursor: pointer;
        }

        input[type="range"]::-moz-range-thumb {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #007bff;
            /* Bootstrap primary color */
            cursor: pointer;
        }

        input[type="range"]::-ms-thumb {
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background: #007bff;
            /* Bootstrap primary color */
            cursor: pointer;
        }
    </style>

    <div class="container-xxl flex-grow-1 container-p-y">

        <div class="card" style="display: grid;height: 100%;">
            <div class="row" style=" padding: 18px;">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="colorPicker" style="font-size: 15px;">Choose line color </label>
                        <input type="color" id="colorPicker" class="form-control"
                            @if (isset($draw['color'])) value="{{ $draw['color'] }}" @endif>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="lineWidth" style="font-size: 15px;">Line width </label>
                        <input type="range" style=" margin-top: 19px; "
                            @if (isset($draw['width'])) value="{{ $draw['width'] }}" @endif id="lineWidth"
                            class="form-control" min="1" max="20">
                    </div>
                </div>
            </div>


            <div class="row" style=" padding: 0px; margin: 0px; ">
                <div class="col-md-4">
                    <video id="video" style="margin-top: 20%;width: 100%" controls>
                        <source src="{{ $result['stream_url'] }}" type="video/mp4">
                        Your browser does not support the video tag.
                    </video>
                </div>
                <div class="col-md-2" style="align-content: space-around;">
                    <button id="extractFrameButton" class="btn btn-primary btn-sm" style=" height: max-content;">Load
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#ffffff"
                            viewBox="0 0 256 256">
                            <path
                                d="M237.66,122.34l-96-96A8,8,0,0,0,128,32V72H48A16,16,0,0,0,32,88v80a16,16,0,0,0,16,16h80v40a8,8,0,0,0,13.66,5.66l96-96A8,8,0,0,0,237.66,122.34ZM144,204.69V176a8,8,0,0,0-8-8H48V88h88a8,8,0,0,0,8-8V51.31L220.69,128Z">
                            </path>
                        </svg>
                    </button>
                    <button id="removeButton" class="btn btn-danger btn-sm"
                        style="height: fit-content;">Undo <svg
                            xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#ffffff"
                            viewBox="0 0 256 256">
                            <path
                                d="M232,112a64.07,64.07,0,0,1-64,64H51.31l34.35,34.34a8,8,0,0,1-11.32,11.32l-48-48a8,8,0,0,1,0-11.32l48-48a8,8,0,0,1,11.32,11.32L51.31,160H168a48,48,0,0,0,0-96H80a8,8,0,0,1,0-16h88A64.07,64.07,0,0,1,232,112Z">
                            </path>
                        </svg></button>
                </div>
                <div class="col-md-6">

                    <div class="row">
                        <div class="col-md-12">
                            <canvas width="500" height="350" id="canvas"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row" style=" text-align: center; padding: 24px; display: block;">

                <form id="dataForm" action="{{ route('attendance.line') }}" method="post">
                    @csrf
                    <input type="hidden" id="start_x" name="start_x" />
                    <input type="hidden" id="start_y" name="start_y" />
                    <input type="hidden" id="end_x" name="end_x" />
                    <input type="hidden" id="end_y" name="end_y" />
                    <input type="hidden" id="color" name="color" />
                    <input type="hidden" id="width" name="width" />
                    <button type="submit" class="btn btn-info btn-sm">Create Line</button>
                </form>

            </div>
            <div id="loading" style=" text-align: center; padding: 51px;display: none;">
                <img src="{{ asset('infinite-spinner.svg') }}" style="width:300px;" />
            </div>

        </div>
    </div>

    <script>
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const extractFrameButton = document.getElementById('extractFrameButton');
        const removeButton = document.getElementById('removeButton');
        const colorPicker = document.getElementById('colorPicker');
        const lineWidthInput = document.getElementById('lineWidth');
        // const getLineInfoButton = document.getElementById('getLineInfoButton');

        let isDrawing = false;
        let isDragging = false;
        let startY = 0;
        let lineDrawn = false;
        let line = null;
        let lineColor = colorPicker.value;
        let lineWidth = parseInt(lineWidthInput.value);

        extractFrameButton.addEventListener('click', () => {
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

            if (line) {
                drawLineManual(line.startX, line.startY, line.endX, line.endY, line.color, line.width);
            }

        });

        canvas.addEventListener('mousedown', (e) => {
            const {
                offsetX,
                offsetY
            } = e;
            if (line && isPointOnLine(offsetX, offsetY)) {
                isDragging = true;
            } else if (!lineDrawn) {
                startY = offsetY;
                isDrawing = true;
            }
        });

        canvas.addEventListener('mousemove', (e) => {
            if (isDrawing) {
                const endX = e.offsetX;
                const endY = startY;
                drawCanvas();
                drawLine(0, startY, endX, endY);
            } else if (isDragging && line) {
                const {
                    offsetY
                } = e;
                line.startY = offsetY;
                line.endY = offsetY;
                drawCanvas();
            }
        });

        canvas.addEventListener('mouseup', (e) => {
            if (isDrawing) {
                const endX = e.offsetX;
                const endY = startY;
                line = {
                    startX: 0,
                    startY,
                    endX,
                    endY,
                    color: lineColor,
                    width: lineWidth
                };
                lineDrawn = true;
                isDrawing = false;
                console.log(line);
            }
            isDragging = false;
        });

        canvas.addEventListener('mouseout', (e) => {
            isDrawing = false;
            isDragging = false;
        });

        removeButton.addEventListener('click', () => {
            line = null;
            lineDrawn = false;
            drawCanvas();
        });

        colorPicker.addEventListener('input', (e) => {
            lineColor = e.target.value;
            drawCanvas();
        });

        lineWidthInput.addEventListener('input', (e) => {
            lineWidth = e.target.value;
            drawCanvas();
        });

        // getLineInfoButton.addEventListener('click', () => {

        // });

        function drawLine(x1, y1, x2, y2) {
            ctx.strokeStyle = lineColor;
            ctx.lineWidth = lineWidth;
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
            ctx.closePath();
        }

        function drawCanvas() {
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            if (line) {
                ctx.strokeStyle = line.color;
                ctx.lineWidth = line.width;
                drawLine(line.startX, line.startY, line.endX, line.endY);
            }
        }

        function isPointOnLine(x, y) {
            if (!line) return false;
            const {
                startY,
                width
            } = line;
            return y >= startY - width / 2 && y <= startY + width / 2;
        }

        // Function to draw a line
        function drawLineManual(x1, y1, x2, y2, color, width) {
            ctx.strokeStyle = color;
            ctx.lineWidth = width;
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
            ctx.closePath();

            line = {
                startX: x1,
                startY: y1,
                endX: x2,
                endY: y2,
                color: color,
                width: width
            };
            lineDrawn = true;
            isDrawing = false;
            console.log(line);
        }

        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('dataForm');
            const responseDiv = document.getElementById('response');

            form.addEventListener('submit', function(e) {
                e.preventDefault();

                if (line) {
                    document.getElementById('loading').style.display = "block";
                    document.getElementById('start_x').value = line.startX;
                    document.getElementById('start_y').value = line.startY;
                    document.getElementById('end_x').value = line.endX;
                    document.getElementById('end_y').value = line.endY;
                    document.getElementById('color').value = colorPicker.value;
                    document.getElementById('width').value = lineWidthInput.value;

                    const formData = new FormData(form);
                    const data = {};

                    formData.forEach((value, key) => {
                        data[key] = value;
                    });

                    fetch('{{ route('attendance.line') }}', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content')
                            },
                            body: JSON.stringify(data)
                        })
                        .then(response => response.json())
                        .then(data => {
                            document.getElementById('loading').style.display = "none";
                            if (data.status == 200) {
                                Swal.fire({
                                    title: "Good job!",
                                    text: "Line is created successfully",
                                    icon: "success"
                                });
                            }else{
                                Swal.fire({
                                    title: "Error!",
                                    text: "Sorry try again",
                                    icon: "error"
                                });
                            }
                           
                            //responseDiv.innerHTML = `<p>${data.message}</p>`;
                        }).catch(error => {
                            document.getElementById('loading').style.display = "none";
                            console.error('Error:', error)
                        });

                } else {
                    alert('No line drawn. or no any changings found');

                }
            });
        });
    </script>

    @if ($draw)
        <script>
            drawLineManual("{{ $draw['start_x'] }}", "{{ $draw['start_y'] }}", "{{ $draw['end_x'] }}", "{{ $draw['end_y'] }}",
                "{{ $draw['color'] }}", "{{ $draw['width'] }}");
        </script>
    @endif
@endSection
