/* ----------------------------------------------------------------------------
 * Easy!Appointments - Open Source Web Scheduler
 *
 * @package     EasyAppointments
 * @author      A.Tselegidis <alextselegidis@gmail.com>
 * @copyright   Copyright (c) 2013 - 2018, Alex Tselegidis
 * @license     http://opensource.org/licenses/GPL-3.0 - GPLv3
 * @link        http://easyappointments.org
 * @since       v1.0.0
 * ---------------------------------------------------------------------------- */

(function () {

    'use strict';

    /**
     * CompanyHelper
     *
     * This class contains the methods that will be used by the "company" tab of the page.
     *
     * @class CompanyHelper
     */
    function CompanyHelper() {
        this.filterResults = {};

    }

    CompanyHelper.prototype.bindEventHandlers = function () {
        var instance = this;

        /**
         * Event: Filter companys Form "Submit"
         *
         * @param {jQuery.Event} event
         */



        $('#filter-company form').submit(function (event) {
            var key = $('#filter-company .key').val();
            $('#filter-company .selected').removeClass('selected');
            instance.resetForm();
            instance.filter(key);
            return false;
        });

        /**
         * Event: Filter company Cancel Button "Click"
         */
        $('#filter-company .clear').click(function () {
            $('#filter-company .key').val('');
            instance.filter('');
            instance.resetForm();
        });

        /**
         * Event: Filter company Row "Click"
         *
         * Display the selected company data to the user.
         */
        $(document).on('click', '.company-row', function () {
            if ($('#filter-company .filter').prop('disabled')) {
                $('#filter-company .results').css('color', '#AAA');
                return; // exit because we are on edit mode
            }

            var companyId = $(this).attr('data-id');
            var company = {};
            $.each(instance.filterResults, function (index, item) {
                if (item.id === companyId) {
                    company = item;
                    return false;
                }
            });

            // Add dedicated provider link.
            var dedicatedUrl = GlobalVariables.baseUrl + '/index.php?company=' + encodeURIComponent(company.hash_id)+'|'+encodeURIComponent(company.id);
            var linkHtml = '<a href="' + dedicatedUrl + '"><span class="glyphicon glyphicon-link"></span></a>';
            $('#companys .record-details h3')
                .find('a')
                .remove()
                .end()
                .append(linkHtml);

            instance.display(company);
            $('#filter-company .selected').removeClass('selected');
            $(this).addClass('selected');
            $('#edit-company, #delete-company, #viewlocations-company, #gotolink-company').prop('disabled', false);

        });

        /**
         * Event: Add New company Button "Click"
         */
        $('#add-company').click(function () {
            instance.resetForm();
            $('#company .add-edit-delete-group').hide();
            $('#company .save-cancel-group').show();
            $('#company .record-details').find('input, textarea').prop('readonly', false);
            $('#company .record-details').find('select').prop('disabled', false);
            $('#filter-company button').prop('disabled', true);
            $('#filter-company .results').css('color', '#AAA');
        });

        /**
         * Event: Cancel company Button "Click"
         *
         * Cancel add or edit of a company record.
         */
        $('#cancel-company').click(function () {
            var id = $('#company-id').val();
            instance.resetForm();
            if (id !== '') {
                instance.select(id, true);
            }
        });

        /**
         * Event: Save company Button "Click"
         */
        $('#save-company').click(function () {
            var company = {
                name: $('#company-name').val(),
                backgroundcolor: $('#company-backgroundcolor').val(),
                topheader: $('#company-topheader').val(),
                logolink: $('#company-logolink').val(),
                width: $('#company-width').val(),
                leng: $('#company-leng').val(),
            };


            if ($('#company-id').val() !== '') {
                company.id = $('#company-id').val();
            }

            if (!instance.validate()) {
                return;
            }

            instance.save(company);
        });

        /**
         * Event: Edit company Button "Click"
         */
        $('#edit-company').click(function () {
            $('#company .add-edit-delete-group').hide();
            $('#company .save-cancel-group').show();
            $('#company .record-details').find('input, textarea').prop('readonly', false);
            $('#company .record-details select').prop('disabled', false);

            $('#filter-company button').prop('disabled', true);
            $('#filter-company .results').css('color', '#AAA');
        });
        $('#viewlocations-company').click(function () {
            window.open(GlobalVariables.baseUrl +'/index.php/backend/users'+'?company='+$('#company-id').val(), '_blank').focus();

        });

        $('#gotolink-company').click(function () {
            var companyId = $('#company-id').val();
            var company = {};
            $.each(instance.filterResults, function (index, item) {
                if (item.id === companyId) {
                    company = item;
                    return false;
                }
            });

            var dedicatedUrl = GlobalVariables.baseUrl + '/index.php?company=' + encodeURIComponent(company.hash_id);
            window.open(dedicatedUrl, '_blank').focus();

        });
        /**
         * Event: Delete company Button "Click"
         */
        $('#delete-company').click(function () {
            var companyId = $('#company-id').val();
            var buttons = [
                {
                    text: EALang.delete,
                    click: function () {
                        instance.delete(companyId);
                        $('#message_box').dialog('close');
                    }
                },
                {
                    text: EALang.cancel,
                    click: function () {
                        $('#message_box').dialog('close');
                    }
                }
            ];

            GeneralFunctions.displayMessageBox(EALang.delete,
                EALang.delete_record_prompt, buttons);
        });
    };


    /**
     * Save company record to database.
     *
     * @param {Object} company Contains the company record data. If an 'id' value is provided
     * then the update operation is going to be executed.
     */
    CompanyHelper.prototype.save = function (company) {
        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_company';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            company: JSON.stringify(company)
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            Backend.displayNotification('Company successfully saved');
            this.resetForm();
            $('#filter-company .key').val('');
            this.filter('', response.id, true);
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Delete a company record from database.
     *
     * @param {Number} id Record ID to be deleted.
     */

    CompanyHelper.prototype.delete = function (companyId) {
        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_delete_company';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            company_id: companyId
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            Backend.displayNotification('Company Deleted');

            this.resetForm();
            this.filter($('#filter-company .key').val());
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Validates a company record.
     *
     * @return {Boolean} Returns the validation result.
     */
    CompanyHelper.prototype.validate = function () {
        $('#company .has-error').removeClass('has-error');

        try {
            // validate required fields.
            var missingRequired = false;

            $('#companys .required').each(function () {
                if ($(this).val() == '' || $(this).val() == undefined) {
                    $(this).closest('.form-group').addClass('has-error');
                    missingRequired = true;
                }
            });

            if (missingRequired) {
                throw EALang.fields_are_required;
            }


            return true;
        } catch (exc) {
            return false;
        }
    };

    /**
     * Resets the company tab form back to its initial state.
     */
    CompanyHelper.prototype.resetForm = function () {
        $('#company .record-details').find('input, textarea').val('');
        $('#company .add-edit-delete-group').show();
        $('#company .save-cancel-group').hide();
        $('#edit-company, #delete-company, #viewlocations-company, #gotolink-company').prop('disabled', true);
        $('#company .record-details').find('input, textarea').prop('readonly', true);
        $('#company .record-details').find('select').prop('disabled', true);
        $('#filter-company .selected').removeClass('selected');
        $('#filter-company button').prop('disabled', false);
        $('#filter-company .results').css('color', '');
    };

    /**
     * Display a company record into the company form.
     *
     * @param {Object} company Contains the company record data.
     */
    CompanyHelper.prototype.display = function (company) {
        $('#company-id').val(company.id);
        $('#company-name').val(company.name);
        $('#company-backgroundcolor').val(company.backgroundcolor);
        $('#company-topheader').val(company.topheader);
        $('#company-logolink').val(company.logolink);
        $('#company-width').val(company.width);
        $('#company-leng').val(company.leng);
    };

    /**
     * Filters company records depending a string key.
     *
     * @param {String} key This is used to filter the company records of the database.
     * @param {Number} selectId Optional, if set then after the filter operation the record with this
     * ID will be selected (but not displayed).
     * @param {Boolean} display Optional (false), if true then the selected record will be displayed on the form.
     */
    CompanyHelper.prototype.filter = function (key, selectId, display) {
        display = display || false;

        var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_filter_company';
        var postData = {
            csrfToken: GlobalVariables.csrfToken,
            key: key
        };

        $.post(postUrl, postData, function (response) {
            if (!GeneralFunctions.handleAjaxExceptions(response)) {
                return;
            }

            this.filterResults = response;

            $('#filter-company .results').html('');
            $.each(response, function (index, company) {
                var html = CompanyHelper.prototype.getFilterHtml(company);
                $('#filter-company .results').append(html);
            });

            if (response.length === 0) {
                $('#filter-company .results').html('<em>' + EALang.no_records_found + '</em>');
            }

            if (selectId !== undefined) {
                this.select(selectId, display);
            }
        }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
    };

    /**
     * Get Filter HTML
     *
     * Get a company row HTML code that is going to be displayed on the filter results list.
     *
     * @param {Object} company Contains the company record data.
     *
     * @return {String} The HTML code that represents the record on the filter results list.
     */
    CompanyHelper.prototype.getFilterHtml = function (company) {
        var html =
            '<div class="company-row entry" data-id="' + company.id + '">' +
            '<strong>' +company.name + '</strong><br>' +
            '</div><hr>';

        return html;
    };

    /**
     * Select a specific record from the current filter results. If the company id does not exist
     * in the list then no record will be selected.
     *
     * @param {Number} id The record id to be selected from the filter results.
     * @param {Boolean} display Optional (false), if true then the method will display the record on the form.
     */
    CompanyHelper.prototype.select = function (id, display) {
        display = display || false;

        $('#filter-company .selected').removeClass('selected');

        $('#filter-company .company-row').each(function () {
            if ($(this).attr('data-id') == id) {
                $(this).addClass('selected');
                return false;
            }
        });

        if (display) {
            $.each(this.filterResults, function (index, company) {
                if (company.id == id) {
                    this.display(company);
                    $('#edit-company, #delete-company, #viewlocations-company, #gotolink-company').prop('disabled', false);
                    return false;
                }
            }.bind(this));
        }
    };

    window.CompanyHelper = CompanyHelper;
})();
