@extends('layouts.layouts_ipad.layouts_Newipad')

@section('modal')
@endsection

@section('style')
    <style>
        .images-box {
            /* height: 960px; */
            width: 100%;
        }

    </style>
@endsection


@section('content')

    <div class="row m-0 p-3">
        <div class="col-12 mb-3">
            <span class="text-white fs-16">
                Patient Detail : &ensp; &ensp; &ensp;
                {{ @$case->hn }} &ensp; &ensp; &ensp;
                {{ @$patient->firstname . ' ' . @$patient->middlename . ' ' . @$patient->lastname }} &ensp; &ensp; &ensp;
                @php
                    $gender = isset($patient->gender) ? 'Male' : 'Female';

                @endphp

                Gender: {{ $gender }} &ensp; &ensp; &ensp;
                {{ @$patient->birthdate }} / {{ age(@$patient->birthdate) }}
            </span>
        </div>








            <div class="col-12 text-white">
                Procedure : {{ @$procedurename }}
            </div>
            @php
                $photoname = mePHOTO($case->case_hn, $image_name, $folderdate).'?a='.RandomString();
            @endphp
              <div class="col-12 text-end mb-3">
                <button type="button" id="pen_btn" hidden></button>
                <button type="button" id="undo" class="btn btn-danger btn-label waves-effect w-lg right waves-light"><i
                        class="ri-arrow-go-back-line label-icon align-middle fs-16 ms-2"></i> Redo</button>

                        <button type="button" id="confirm" class="btn btn-primary btn-label waves-effect w-lg right ms-2 waves-light"><i
                            class="ri-check-double-line label-icon align-middle fs-16 ms-2"></i> Confirm</button>
            </div>

                <div id="image_div" class="col-12 mt-2">
                    <img src="{{@$photoname}}" id="image" class="images-box" alt="">
                </div>
                <div id="crop_div" style="display: none">
                    <canvas width="4000" height="2500" style="width: 900px; height: 760px;"></canvas>
                    {{-- <canvas class="images-box" id="drawing_canvas"></canvas> --}}
                </div>


            <form action="{{url('tablet/procedure')}}" method="post" id="drawing_form" hidden>
                @csrf
                <input type="text" name="event" value="save_drawing">
                <input type="text" name="cid"  value="{{@$case->_id}}">
                <input type="text" name="hn"  value="{{@$case->case_hn}}">
                <input type="text" name="folderdate"  value="{{@$folderdate}}">
                <input type="text" name="photoname"  value="{{@$image_name}}">
                <input type="text" name="photodata" id="photodata">
            </form>





    </div>
@endsection


@section('script')

<script>
    var cropper, canvas, cv, ctx, old_canvas;
    var from_x, from_y, to_x, to_y;

    var down                = false
    var is_crop             = false
    var has_input           = false
    var warning_crop        = false
    var props               = []
    var croppers            = {}
    var div_width           = $('#image_div').width()
    var div_height          = $('#image_div').height()
    var selected_text       = ''
    var canvas_hist         = []
    var tracked_textarr     = {}
    var tracked_btn         = ''
    var tracked_cvhist      = 0 // all drawing
    var tracked_elem        = 0
    var is_undo             = false
    var is_redo             = false

    var image;
    var image_src;

    var is_submit = false

    document.addEventListener("DOMContentLoaded", function(){
        loadJS("{{ url('public/cropnew/cropper.min.js') }}", true)
    });

    function loadJS(FILE_URL, async = true) {
        let scriptEle = document.createElement("script");

        scriptEle.setAttribute("src", FILE_URL);
        scriptEle.setAttribute("type", "text/javascript");
        scriptEle.setAttribute("async", async);

        document.body.appendChild(scriptEle);

        $('#confirm').prop('disabled', true)
        $('#undo').prop('disabled', true)
        $('#crop_div').css('display', 'none')


        // success event
        scriptEle.addEventListener("load", () => {
            console.log("File loaded")
            // image = document.querySelector('#image');
            // image_src = $(image).attr('src')
            // cropper = create_cropper_instance(image)
            initializeCropper();
        });
        // error event
        scriptEle.addEventListener("error", (ev) => {
            console.log("Error on loading file", ev);
        });
    }

    function initializeCropper() {
        const image = document.getElementById('image');
        image_src = $(image).attr('src')
        if (image.complete && image.naturalHeight !== 0) {
            cropper = create_cropper_instance(image)
        } else {
            image.onload = () => {
                cropper = create_cropper_instance(image)
            };
        }
    }

    function create_cropper_instance(img, viewmode=1, action=''){
        let cropper = new Cropper(img, {
            dragMode: 'move',
            autocrop: false,
            background: true,
            viewMode: viewmode,
            // minContainerHeight: 800,
            minContainerWidth: 1200,
            minContainerHeight: div_height,
            // minContainerWidth: div_width,
            zoomable: false,
            zoomOnTouch: false,
            movable: false,
            autoCropArea: 1,
            ready: function() {
                $('.cropper-crop-box').css('display', 'none')
                detect_crop_image()
                $('#pen_btn').trigger('click')
            },
        });
        return cropper
    }

    function setupCanvas(canvas) {
        let dpr = window.devicePixelRatio || 1;
        let rect = canvas.getBoundingClientRect();
        canvas.width = rect.width * dpr;
        canvas.height = rect.height * dpr;
        let ctx = canvas.getContext('2d');
        ctx.scale(dpr, dpr);
        return ctx;
    }

    function detect_crop_image(){
        let base64 = cropper.getCroppedCanvas().toDataURL()
        let is_crop = $('#crop_div').css('display')
        $('#crop_div').css('display', 'block')

        // $('#crop_div').html('')
        // $('#crop_div').append(cropper.getCroppedCanvas({
        //     minWidth: 900, minHeight: 960,maxWidth:900,maxHeight: 960,
        //     // minWidth: img.width, minHeight: img.height,maxWidth:img.width,maxHeight: img.height,
        //     imageSmoothingEnabled: true,
        //     imageSmoothingQuality: 'high',
        // }))

        // $('#crop_div').append(cropper.getCroppedCanvas({minWidth: div_width+50, minHeight: div_height,maxWidth: div_width+50,maxHeight: div_height,}))

        $('#image_div').css('display', 'none')
        $('#confirm').prop('disabled', false)
        $('#undo').prop('disabled', false)


        let cv_index =  $('canvas').length == 1 ? 0 : 1
        canvas       = $('canvas').get(cv_index)
        // ctx         = canvas.getContext('2d')
        ctx         = setupCanvas(canvas)
        cv          = $('canvas').get(cv_index)
        props['w']  = canvas.width
        props['h']  = canvas.height

        let img = new Image();
        img.onload = function() {
            ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width / window.devicePixelRatio, canvas.height / window.devicePixelRatio);
            canvas_hist.push(img_to_base64())
            init_image = img_to_base64()
        };
        img.src = base64;

        $('#photodata').val(base64)
    }

    function clear_hist(){
        if(is_undo){
            let new_canvas_hist = []
            for (let i = 0; i <= tracked_elem; i++) {
                new_canvas_hist.push(canvas_hist[i])
            }

            canvas_hist = new_canvas_hist
            tracked_elem = canvas_hist.length - 1
            is_undo = false
            is_redo = false
        }
    }

    $('#undo').on('click', function (e) {
        e.preventDefault()
        is_undo = true
        is_redo = false
        if(tracked_elem <= 0){
            tracked_elem = 0
        }
        if(tracked_elem == 1){
            tracked_elem = 1
        }
        if(tracked_elem > 0){
            tracked_elem = tracked_elem - 1
        }
        redrawing(tracked_elem)
    })

    $('#confirm').on('click', function (e) {
        e.preventDefault()
        let img_base64 = img_to_base64()
        $('#photodata').val(img_base64)
        if(is_submit == false){
            $(this).prop('disabled', true)
            $('#drawing_form').submit()
        }
    })


    function redrawing(index){
        let canvasdata  = canvas_hist[index]
        let newImage    = new Image()
        newImage.onload = function () {
            // ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height)
            ctx.drawImage(newImage, 0, 0, newImage.width, newImage.height, 0, 0, canvas.width / window.devicePixelRatio, canvas.height / window.devicePixelRatio);
        }
        newImage.src    = canvasdata
    }

    function img_to_base64(){
        // let this_canvas = document.getElementById('drawing_canvas');
        let this_canvas = document.querySelector('canvas');
        let crop_cv     = $(this_canvas).get(0);
        let crop_src    = $(crop_cv).attr('src')
        let canvas      = document.createElement('canvas');
        let ctx         = canvas.getContext('2d');
        // canvas.width    = crop_cv.width;
        // canvas.height   = crop_cv.height;
        // ctx.drawImage(crop_cv, 0, 0);

        let maxWidth = 900
        let maxHeight = 760
        canvas.width = maxWidth;
        canvas.height = maxHeight;
        ctx.drawImage(crop_cv, 0, 0, crop_cv.width, crop_cv.height, 0, 0, maxWidth, maxHeight);

        // return canvas.toDataURL('image/png');
        let quality = 0.9
        return canvas.toDataURL('image/jpeg', quality);
        // let dataurl = cropper.getCroppedCanvas({minWidth: div_width, minHeight: div_height,maxWidth: div_width,maxHeight: div_height,}).toDataURL()
        // return dataurl
    }

    $('#pen_btn').on('click', function(){
        unbind_event()

        $(cv).bind('mousedown touchstart', function (e) {
            e.preventDefault()
            set_position(e, 'to')
            down = true
            $(cv).bind('mousemove touchmove', function (e) {
                e.preventDefault()
                draw_pen(e)
                set_position(e, 'to')
            })
        })

        $(cv).bind('mouseup touchend', function (e) {
            e.preventDefault()

            down = false
            clear_hist()
            canvas_hist.push(img_to_base64())
            tracked_cvhist = canvas_hist.length
            tracked_elem += 1
            $(cv).unbind('mousemove touchmove')
        })
    })

    function unbind_event(){
        $(cv).unbind('mouseup touchend')
        $(cv).unbind('mousedown touchstart')
        $(cv).unbind('mousemove touchmove')
    }

    function set_position(e, type){
        let position = getCursorPosition(canvas, e)
        if(type == 'from'){
            from_x = position[0]
            from_y = position[1]
        } else if(type == 'to'){
            to_x = position[0]
            to_y = position[1]
        }
    }

    function getCursorPosition(canvas, event) {
        let rect    = canvas.getBoundingClientRect()
        let x, y
        if(event.touches){
            let touch = event.touches[0]
            x = touch.clientX - rect.left
            y = touch.clientY - rect.top
        } else {
            x  = event.clientX - rect.left
            y  = event.clientY - rect.top
        }

        return [x, y]
    }

    function draw_pen(e){
        e.preventDefault()
        if (!down) return;
        ctx.beginPath();
        ctx.lineCap = 'round';
        ctx.fillStyle = '#03396c'
        ctx.lineWidth = 20
        ctx.strokeStyle = '#03396c'
        ctx.moveTo(to_x, to_y);
        set_position(e, 'to')
        ctx.lineTo(to_x, to_y);
        ctx.stroke();

    }
</script>


@endsection
