//
//   Copyright © 2021,2022 IsardVDI S.L.
//
//   This file is part of DD
//
//   DD is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Affero General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or (at your
//   option) any later version.
//
//   DD is distributed in the hope that it will be useful, but WITHOUT ANY
//   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
//   FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
//   details.
//
//   You should have received a copy of the GNU Affero General Public License
//   along with DD. If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

$(document).ready(function() {

    $('.icon-dropdown').select2({
        width: "100%",
        templateSelection: formatText,
        templateResult: formatText
    });

    function formatText (icon) {
        return $('<span><i class="fa ' + $(icon.element).data('icon') + '"></i> ' + icon.text + '</span>');
    };

    // Update background input when colorpicker is used
    $('#colorpicker-background').colorpicker().on('changeColor', function (e) {
        $('#colorpicker-background-input').val(e.color.toHex());
    });

    // Update background colorpicker when input is used
    $('#colorpicker-background-input').on('keyup', function (e) {
        if ($('#colorpicker-background-input').val()[0] == '#' && $('#colorpicker-background-input').val().length == 7) {
            $('#colorpicker-background').colorpicker('setValue', $('#colorpicker-background-input').val());
        }
    })

    // Update primary input when colorpicker is used
    $('#colorpicker-primary').colorpicker().on('changeColor', function (e) {
        $('#colorpicker-primary-input').val(e.color.toHex());
    });

    // Update primary colorpicker when input is used
    $('#colorpicker-primary-input').on('keyup', function (e) {
        if ($('#colorpicker-primary-input').val()[0] == '#' && $('#colorpicker-primary-input').val().length == 7) {
            $('#colorpicker-primary').colorpicker('setValue', $('#colorpicker-primary-input').val());
        }
    })

    // Update secondary input when colorpicker is used
    $('#colorpicker-secondary').colorpicker().on('changeColor', function (e) {
        $('#colorpicker-secondary-input').val(e.color.toHex());
    });

    // Update primary colorpicker when input is used
    $('#colorpicker-secondary-input').on('keyup', function (e) {
        if ($('#colorpicker-secondary-input').val()[0] == '#' && $('#colorpicker-secondary-input').val().length == 7) {
            $('#colorpicker-secondary').colorpicker('setValue', $('#colorpicker-secondary-input').val());
        }
    })

    init_logo_cropper()
    init_background_cropper()

    $('#save-colors').click(function () {
        // console.log({
        //     'background': $('#colorpicker-background-input').val(),
        //     'primary': $('#colorpicker-primary-input').val(),
        //     'secondary': $('#colorpicker-secondary-input').val()
        // })
        $.ajax({
            type: "PUT",
            url:"/api/dashboard/colours",
            data: JSON.stringify({
                'background': $('#colorpicker-background-input').val(),
                'primary': $('#colorpicker-primary-input').val(),
                'secondary': $('#colorpicker-secondary-input').val()
            }),
            success: function(data)
            {
                $('#colorpicker-background').attr('data-container', data.colours.background);
                $('#colorpicker-background-input').val(data.colours.background);
                $('#colorpicker-primary').attr('data-container', data.colours.primary);
                $('#colorpicker-primary-input').val(data.colours.primary);
                $('#colorpicker-secondary').attr('data-container', data.colours.secondary);
                $('#colorpicker-secondary-input').val(data.colours.secondary);
            },
            error: function(data)
            {
                console.log('ERROR!')
                console.log(data)
            }
        });
    })

    $('#save-menu').click(function () {
        ids = $('[id^="apps_external-"]')
        var menu_options = {};
        ids.each(function( index ) {
            // console.log(ids[index].id)
            if(!(ids[index].id.split('-')[1] in menu_options)){
                menu_options[ids[index].id.split('-')[1]]={}
            }
            menu_options[ids[index].id.split('-')[1]][ids[index].id.split('-')[2]]=$('#'+ids[index].id).val()
        })
        $.ajax({
            type: "PUT",
            url:"/api/dashboard/menu",
            data: JSON.stringify(menu_options),
            success: function(data)
            {
                // $('#colorpicker-background').attr('data-container', data.colours.toHex());
                // $('#colorpicker-background-input').val(data.colours.toHex());
                // $('#colorpicker-primary').attr('data-container', data.colours.toHex());
                // $('#colorpicker-primary-input').val(data.colours.toHex());
                // $('#colorpicker-secondary').attr('data-container', data.colours.toHex());
                // $('#colorpicker-secondary-input').val(data.colours.toHex());
            },
            error: function(data)
            {
                console.log('ERROR!')
            }
        });
    })

})

/* CROPPER */


function init_logo_cropper() {


    if (typeof ($.fn.cropper) === 'undefined') { return; }
    // console.log('init_logo_cropper');

    var $image = $('#image_logo');
    var $dataX = $('#dataX');
    var $dataY = $('#dataY');
    var $dataHeight = $('#dataHeight');
    var $dataWidth = $('#dataWidth');
    var $dataRotate = $('#dataRotate');
    var $dataScaleX = $('#dataScaleX');
    var $dataScaleY = $('#dataScaleY');
    var cropWidth = 80;
    var cropHeight = 45;
    var aspectRatio = cropWidth / cropHeight;
    var options = {
        aspectRatio: aspectRatio,
        preview: '.img-preview-logo',
        crop: function (e) {
            $dataX.val(Math.round(e.x));
            $dataY.val(Math.round(e.y));
            $dataHeight.val(Math.round(e.height));
            $dataWidth.val(Math.round(e.width));
            $dataRotate.val(e.rotate);
            $dataScaleX.val(e.scaleX);
            $dataScaleY.val(e.scaleY);
        }
    };


    // Tooltip
    $('[data-toggle="tooltip"]').tooltip();


    // Cropper
    $image.on({
        'build.cropper': function (e) {
            // console.log(e.type);
        },
        'built.cropper': function (e) {
            // console.log(e.type);
        },
        'cropstart.cropper': function (e) {
            // console.log(e.type, e.action);
        },
        'cropmove.cropper': function (e) {
            // console.log(e.type, e.action);
        },
        'cropend.cropper': function (e) {
            // console.log(e.type, e.action);
        },
        'crop.cropper': function (e) {
            // console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY);
        },
        'zoom.cropper': function (e) {
            // console.log(e.type, e.ratio);
        }
    }).cropper(options);

    $('#save-logo-crop').click(function () {
        $image.data('cropper').getCroppedCanvas({ width: cropWidth, height: cropHeight }).toBlob(function (blob) {
            var uri = URL.createObjectURL(blob);
            var img = new Image();

            img.src = uri;
            $('.nav_menu_logo').attr('src', img.src)

            var formData = new FormData();
            formData.append('croppedImage', blob);
            $.ajax('/api/dashboard/logo', {
                method: "PUT",
                data: formData,
                processData: false,
                contentType: false,
                success: function () {
                    // Update logo image
                    $('.nav_menu_logo').attr('src', img.src)
                    console.log('Upload success');
                },
                error: function () {
                console.log('Upload error');
                }
            });
        });
    })

    // Methods
    $('.docs-buttons-logo').on('click', '[data-method]', function () {
        var $this = $(this);
        var data = $this.data();
        var $target;
        var result;

        if ($this.prop('disabled') || $this.hasClass('disabled')) {
            return;
        }

        if ($image.data('cropper') && data.method) {
            data = $.extend({}, data); // Clone a new one

            if (typeof data.target !== 'undefined') {
                $target = $(data.target);

                if (typeof data.option === 'undefined') {
                    try {
                        data.option = JSON.parse($target.val());
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            }

            result = $image.cropper(data.method, data.option, data.secondOption);

            switch (data.method) {
                case 'scaleX':
                case 'scaleY':
                    $(this).data('option', -data.option);
                    break;
            }

            if ($.isPlainObject(result) && $target) {
                try {
                    $target.val(JSON.stringify(result));
                } catch (e) {
                    console.log(e.message);
                }
            }

        }
    });

    // Import image
    var $inputImage = $('#inputImageLogo');
    var URL = window.URL || window.webkitURL;
    var blobURL;

    if (URL) {
        $inputImage.change(function () {
            var files = this.files;
            var file;

            if (!$image.data('cropper')) {
                return;
            }

            if (files && files.length) {
                file = files[0];

                if (/^image\/\w+$/.test(file.type)) {
                    blobURL = URL.createObjectURL(file);
                    $image.one('built.cropper', function () {

                        // Revoke when load complete
                        URL.revokeObjectURL(blobURL);
                    }).cropper('reset').cropper('replace', blobURL);
                    $inputImage.val('');
                } else {
                    window.alert('Please choose an image file.');
                }
            }
        });
    } else {
        $inputImage.prop('disabled', true).parent().addClass('disabled');
    }


};

/* CROPPER --- end */

function init_background_cropper() {


    if (typeof ($.fn.cropper) === 'undefined') { return; }
    // console.log('init_background_cropper');

    var $image = $('#image_background');
    var $dataX = $('#dataX');
    var $dataY = $('#dataY');
    var $dataHeight = $('#dataHeight');
    var $dataWidth = $('#dataWidth');
    var $dataRotate = $('#dataRotate');
    var $dataScaleX = $('#dataScaleX');
    var $dataScaleY = $('#dataScaleY');
    var cropWidth = 1920;
    var cropHeight = 1080;
    var aspectRatio = cropWidth / cropHeight;
    var options = {
        aspectRatio: aspectRatio,
        preview: '.img-preview-background',
        crop: function (e) {
            $dataX.val(Math.round(e.x));
            $dataY.val(Math.round(e.y));
            $dataHeight.val(Math.round(e.height));
            $dataWidth.val(Math.round(e.width));
            $dataRotate.val(e.rotate);
            $dataScaleX.val(e.scaleX);
            $dataScaleY.val(e.scaleY);
        }
    };


    // Tooltip
    $('[data-toggle="tooltip"]').tooltip();


    // Cropper
    $image.on({
        'build.cropper': function (e) {
            // console.log(e.type);
        },
        'built.cropper': function (e) {
            // console.log(e.type);
        },
        'cropstart.cropper': function (e) {
            // console.log(e.type, e.action);
        },
        'cropmove.cropper': function (e) {
            // console.log(e.type, e.action);
        },
        'cropend.cropper': function (e) {
            // console.log(e.type, e.action);
        },
        'crop.cropper': function (e) {
            // console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY);
        },
        'zoom.cropper': function (e) {
            // console.log(e.type, e.ratio);
        }
    }).cropper(options);

    $('#save-background-crop').click(function () {
        $image.data('cropper').getCroppedCanvas({ width: cropWidth, height: cropHeight }).toBlob(function (blob) {
            var uri = URL.createObjectURL(blob);
            var img = new Image();

            img.src = uri;

            var formData = new FormData();
            formData.append('croppedImage', blob);
            $.ajax('/api/dashboard/background', {
                method: "PUT",
                data: formData,
                processData: false,
                contentType: false,
                success: function () {
                    // Update background image
                    // console.log('Upload success');
                },
                error: function () {
                    // console.log('Upload error');
                }
            });
        });
    })

    // Methods
    $('.docs-buttons-background').on('click', '[data-method]', function () {
        var $this = $(this);
        var data = $this.data();
        var $target;
        var result;

        if ($this.prop('disabled') || $this.hasClass('disabled')) {
            return;
        }

        if ($image.data('cropper') && data.method) {
            data = $.extend({}, data); // Clone a new one

            if (typeof data.target !== 'undefined') {
                $target = $(data.target);

                if (typeof data.option === 'undefined') {
                    try {
                        data.option = JSON.parse($target.val());
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            }

            result = $image.cropper(data.method, data.option, data.secondOption);

            switch (data.method) {
                case 'scaleX':
                case 'scaleY':
                    $(this).data('option', -data.option);
                    break;
            }

            if ($.isPlainObject(result) && $target) {
                try {
                    $target.val(JSON.stringify(result));
                } catch (e) {
                    console.log(e.message);
                }
            }

        }
    });

    // Import image
    var $inputImage = $('#inputImageBackground');
    var URL = window.URL || window.webkitURL;
    var blobURL;

    if (URL) {
        $inputImage.change(function () {
            var files = this.files;
            var file;

            if (!$image.data('cropper')) {
                return;
            }

            if (files && files.length) {
                file = files[0];

                if (/^image\/\w+$/.test(file.type)) {
                    blobURL = URL.createObjectURL(file);
                    $image.one('built.cropper', function () {

                        // Revoke when load complete
                        URL.revokeObjectURL(blobURL);
                    }).cropper('reset').cropper('replace', blobURL);
                    $inputImage.val('');
                } else {
                    window.alert('Please choose an image file.');
                }
            }
        });
    } else {
        $inputImage.prop('disabled', true).parent().addClass('disabled');
    }


};