<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">Editeur image</h1>
            </div>
            <div class="modal-body">
                <div class="container m-0 p-0">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="row">
                                <div class="col-sm-12">
                                    <div class="row" id="toolbox">
                                        <div class="col-sm-12 px-2">
                                            <button class="btn btn-outline-dark rounded-pill"
                                                id="toolbox-remove-element">
                                                <i class="uil uil-multiply"></i> Supprimer l'élément
                                            </button>
                                            <button class="btn btn-outline-dark rounded-pill" id="toolbox-clear-canvas">
                                                <i class="uil uil-folder-times"></i> Vider
                                            </button>
                                        </div>
                                        <div class="col-sm-12 px-2">
                                            <label for="toolbox-color">Couleur</label>
                                            <input id="toolbox-color" type="color" autocomplete="off"
                                                class="form-control form-control-color">
                                        </div>
                                        <div class="col-sm-12 px-2" id="toolbox-elements">
                                            <button name="edito" class="btn btn-outline-dark rounded-pill">
                                                <i class="uil uil-text-size"></i> Ajouter text</button>
                                            <input class="form-control w-75 mt-2" type="text"
                                                oninput="input = this.value;" id="edite" placeholder="ajouter text">
                                        </div>
                                        <script>
                                            var inp = document.getElementById('edite')
                                            var input = document.getElementById('edite').value;
                                            var btn = document.getElementsByName('edito')[0];
                                            btn.addEventListener('click', () => {
                                                editor.addTextBox(input);
                                                inp.value = '';
                                                return false;
                                            });
                                        </script>

                                    </div>
                                </div>
                                <div class="col-sm-12 px-2">
                                    <div class="row">
                                        <div class="col-sm-12 px-2">
                                            <button id="drawing-mode" class="btn btn-outline-dark rounded-pill">
                                                <i class="uil uil-palette"></i> Annuler le mode dessin
                                            </button>
                                        </div>
                                    </div>
                                    <div class="row px-2" id="drawing-mode-options">
                                        <div class="col-sm-12" id="drawing-mode-options">
                                            <label for="drawing-mode-selector">Mode:</label>
                                            <select class="form-select rounded-pill" aria-label="Default select example"
                                                id="drawing-mode-selector" autocomplete="off">
                                                <option value="pencil">Pencil</option>
                                                <option value="circle">Circle</option>
                                                <option value="spray">Spray</option>
                                                <option value="pattern">Pattern</option>
                                                <option value="hline">H-Line</option>
                                                <option value="vline">V-Line</option>
                                                <option value="square">Square</option>
                                                <option value="diamond">Diamond</option>
                                                <option value="texture">Texture</option>
                                            </select>
                                        </div>
                                        <div class="col-sm-12">
                                            <label for="drawing-line-width">Largeur de Peinture:</label>
                                            <span class="info">5</span>
                                            <input type="range" class="form-range" value="5" min="0"
                                                max="150" id="drawing-line-width" autocomplete="off">
                                        </div>
                                        <div class="col-sm-12">
                                            <label for="drawing-color">Couleur de la Peinture:</label>
                                            <input type="color" class="form-control form-control-color"
                                                value="#003399" id="drawing-color" autocomplete="off">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-8">
                            <div id="editor">
                                <canvas id="c" width="1" height="1"
                                    style="border: 1px dotted #CCCCCC;">
                                </canvas>
                            </div>
                            <input type="hidden" id="src" value="https://media.istockphoto.com/id/544676786/fr/photo/mosqu%C3%A9e-de-casablanca.jpg?s=612x612&w=0&k=20&c=Ghdq0SbzJ_uyVvi9NDrwgK6O6aeZMhoamW2S3aWNUkA=">

                            <script>
                                var canvasWidth = 900;
                                var canvasHeight = 470;
                                var image =document.getElementById("src").value;
                                console.log(image);
                                var editor = new Smart_FabricJs_EditCanvas('c', image, canvasWidth, canvasHeight, '#FFFFFF');
                                var canvas = editor.getCanvas();
                                canvas.requestRenderAll();

                                // function Editor(img) {
                                //     var canvasWidth = 900;
                                //     var canvasHeight = 470;
                                //     var image = img;
                                //     console.log("func");
                                //     var editor = new Smart_FabricJs_EditCanvas('c', image, canvasWidth, canvasHeight, '#FFFFFF');
                                //     var canvas = editor.getCanvas();
                                //     canvas.requestRenderAll();

                                // }
                            </script>

                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer" id="btn">
                <button class="btn btn-dark" data-bs-dismiss="modal">Fermer</button>
                <button onClick="editor.download()" class="btn btn-danger">save</button>
                {{-- <script>
                    function DownloadCanvasAsImage() {
                        let downloadLink = document.createElement('a');
                        downloadLink.setAttribute('download', 'CanvasAsImage.png');
                        let can = document.getElementById('c');
                        let dataURL = can.toDataURL();
                        let url = dataURL.replace(/^data:image\/png/, 'data:application/octet-stream');
                        downloadLink.setAttribute('href', url);
                        downloadLink.click();
                    }
                </script> --}}
            </div>
            <form id="myForm" action="{{ route('Document.editor',$id) }}" method="post">
            @csrf
                <input type="hidden" name="img" value="" id="edited" >
            </form>
        </div>
    </div>
</div>
<script>
    $('#toolbox-clear-canvas').on('click', function() {
        var ok = confirm('Effacer la zone de dessin ?');
        if (ok) {
            editor.clearCanvas();
        }
        return false;
    });

    $('#toolbox-remove-element').on('click', function() {
        //--
        var ok = confirm("Supprimer l'élément sélectionné de la zone de dessin?");
        if (ok) {
            editor.removeSelected();
        }
        //--
        return false;
        //--
    });
    $('#toolbox-color').on('change', function() {
        //--
        var val = $(this).val();
        //	console.log(val);
        if (!val) {
            return;
        } //end if
        editor.setColorOnSelected('fill', val);
        //--
        return false;
        //--
    });

    $('#toolbox-scolor').on('change', function() {
        //--
        var val = $(this).val();
        //	console.log(val);
        if (!val) {
            return;
        } //end if
        editor.setColorOnSelected('stroke', val);
        //--
        return false;
        //--
    });
    // to json
    // var btnEl = document.createElement("button");
    // btnEl.innerHTML = "Enregistrer";
    // btnEl.classList.add('btn');
    // btnEl.classList.add('btn-primary');
    // btnEl.id = "to-json";
    // document.getElementById("btn").appendChild(btnEl);

    // btnEl.onclick = function() {
    //     smartJ$Browser.VirtualFileDownload(
    //         String(JSON.stringify(canvas, null, 2)),
    //         "drawing.fabric.json",
    //         "application/json",
    //         "UTF-8"
    //     );
    // };
</script>
<script>
    (function() {
        var theTextureImage = '{{ asset('fabric.js/SVG/server.svg') }}';
        var isCanvasDrawingMode = null;
        var drawingModeEl = $('#drawing-mode'),
            drawingOptionsEl = $('#drawing-mode-options'),
            drawingColorEl = $('#drawing-color'),
            drawingShadowColorEl = $('#drawing-shadow-color'),
            drawingLineWidthEl = $('#drawing-line-width'),
            drawingShadowWidth = $('#drawing-shadow-width'),
            drawingShadowOffset = $('#drawing-shadow-offset');
        drawingModeEl.on('click', function() {
            if (isCanvasDrawingMode === null) {
                isCanvasDrawingMode = false;
            } else {
                isCanvasDrawingMode = !isCanvasDrawingMode;
            }
            if (isCanvasDrawingMode) {
                $('#toolbox').hide();
                drawingModeEl.text('Annuler le mode dessin');
                drawingOptionsEl.show();
            } else {
                $('#toolbox').show();
                drawingModeEl.text('Entrer en mode dessin');
                drawingOptionsEl.hide();
            }
            editor.canvasToggleDrawingMode(!!isCanvasDrawingMode);
        }).trigger('click');

        if (fabric.PatternBrush) {

            var vLinePatternBrush = new fabric.PatternBrush(canvas);

            vLinePatternBrush.getPatternSrc = function() {

                var patternCanvas = fabric.document.createElement('canvas');
                patternCanvas.width = patternCanvas.height = 10;
                var ctx = patternCanvas.getContext('2d');

                ctx.strokeStyle = this.color;
                ctx.lineWidth = 5;
                ctx.beginPath();
                ctx.moveTo(0, 5);
                ctx.lineTo(10, 5);
                ctx.closePath();
                ctx.stroke();

                return patternCanvas;
            };

            var hLinePatternBrush = new fabric.PatternBrush(canvas);
            hLinePatternBrush.getPatternSrc = function() {

                var patternCanvas = fabric.document.createElement('canvas');
                patternCanvas.width = patternCanvas.height = 10;
                var ctx = patternCanvas.getContext('2d');

                ctx.strokeStyle = this.color;
                ctx.lineWidth = 5;
                ctx.beginPath();
                ctx.moveTo(5, 0);
                ctx.lineTo(5, 10);
                ctx.closePath();
                ctx.stroke();

                return patternCanvas;
            };

            var squarePatternBrush = new fabric.PatternBrush(canvas);
            squarePatternBrush.getPatternSrc = function() {

                var squareWidth = 10,
                    squareDistance = 2;

                var patternCanvas = fabric.document.createElement('canvas');
                patternCanvas.width = patternCanvas.height = squareWidth + squareDistance;
                var ctx = patternCanvas.getContext('2d');

                ctx.fillStyle = this.color;
                ctx.fillRect(0, 0, squareWidth, squareWidth);

                return patternCanvas;
            };

            var diamondPatternBrush = new fabric.PatternBrush(canvas);
            diamondPatternBrush.getPatternSrc = function() {

                var squareWidth = 10,
                    squareDistance = 5;
                var patternCanvas = fabric.document.createElement('canvas');
                var rect = new fabric.Rect({
                    width: squareWidth,
                    height: squareWidth,
                    angle: 45,
                    fill: this.color
                });

                var canvasWidth = rect.getBoundingRect().width;

                patternCanvas.width = patternCanvas.height = canvasWidth + squareDistance;
                rect.set({
                    left: canvasWidth / 2,
                    top: canvasWidth / 2
                });

                var ctx = patternCanvas.getContext('2d');
                rect.render(ctx);

                return patternCanvas;
            };

            var img = new Image();
            var texturePatternBrush = null;
            img.onload = function() {
                texturePatternBrush = new fabric.PatternBrush(canvas);
                texturePatternBrush.source = this;
            };
            img.src = String(theTextureImage);

        }

        $('#drawing-mode-selector').on('change', function() {
            //--
            theVal = $(this).val() || '';
            //--
            switch (theVal.toLowerCase()) {
                case 'hline':
                    canvas.freeDrawingBrush = hLinePatternBrush;
                    break;
                case 'vline':
                    canvas.freeDrawingBrush = vLinePatternBrush;
                    break;
                case 'square':
                    canvas.freeDrawingBrush = squarePatternBrush;
                    break;
                case 'diamond':
                    canvas.freeDrawingBrush = diamondPatternBrush;
                    break;
                case 'texture':
                    if (texturePatternBrush) {
                        canvas.freeDrawingBrush = texturePatternBrush;
                    } else {
                        console.error('Cannot Load Pattern Image: ' + theTextureImage);
                    }
                    break;
                default:
                    try {
                        canvas.freeDrawingBrush = new fabric[theVal.charAt(0).toUpperCase() + theVal.slice(
                            1) + 'Brush'](canvas);
                    } catch (err) {
                        console.error('Error: ' + err);
                        return;
                    }
            } //end switch
            //--
            if (canvas.freeDrawingBrush) {
                canvas.freeDrawingBrush.color = drawingColorEl.val();
                canvas.freeDrawingBrush.width = parseInt(drawingLineWidthEl.val(), 10) || 1;
                canvas.freeDrawingBrush.shadow = new fabric.Shadow({
                    blur: parseInt(drawingShadowWidth.val(), 10) || 0,
                    offsetX: 0,
                    offsetY: 0,
                    affectStroke: true,
                    color: drawingShadowColorEl.val(),
                });
            }
            //--
        });

        drawingColorEl.on('change', function() {
            canvas.freeDrawingBrush.color = $(this).val();
        });
        drawingShadowColorEl.on('change', function() {
            canvas.freeDrawingBrush.shadow.color = $(this).val();
        });
        drawingLineWidthEl.on('change', function() {
            canvas.freeDrawingBrush.width = parseInt($(this).val(), 10) || 1;
            $(this).prev().text($(this).val());
        });
        drawingShadowWidth.on('change', function() {
            canvas.freeDrawingBrush.shadow.blur = parseInt($(this).val(), 10) || 0;
            $(this).prev().text($(this).val());
        });
        drawingShadowOffset.on('change', function() {
            canvas.freeDrawingBrush.shadow.offsetX =
                canvas.freeDrawingBrush.shadow.offsetY = parseInt($(this).val(), 10) || 0;
            $(this).prev().text($(this).val());
        });

        if (canvas.freeDrawingBrush) {
            canvas.freeDrawingBrush.color = drawingColorEl.val();
            canvas.freeDrawingBrush.width = parseInt(drawingLineWidthEl.val(), 10) || 1;
            canvas.freeDrawingBrush.shadow = new fabric.Shadow({
                blur: parseInt(drawingShadowWidth.val(), 10) || 0,
                offsetX: 0,
                offsetY: 0,
                affectStroke: true,
                color: drawingShadowColorEl.val(),
            });
        }
    })();
</script>
