<!-- Rename Group Modal -->

<style>
    #renameThermostatModal .modal-dialog {
        max-width: 28em;
    }
</style>

<div class="modal fade" id="renameThermostatModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h3 class="modal-title" data-translateid="text_rename_thermostat">Rename thermostat</h3>
            </div>
            <div class="modal-body">
                <div class="form-group has-feedback">
                    <label class="control-label" data-translateid="text_name" for="inputRenameThermostat">Name</label>
                    <input id="inputRenameThermostat" type="text" required class="form-control"
                        data-validator-cb="verifyThermostatRename" aria-describedby="helpBlock" placeholder=""
                        autocorrect="off" spellcheck="false" maxlength="32">
                    <div class="glyphicon glyphicon-remove form-control-feedback"></div>
                    <span class="text-danger"></span>
                    <!--
					<span id="helpBlock" class="help-block"><span data-translateid="text_note">Note:</span> <br> <span data-translateid="text_groupRename">Group rename can be edited at any time.</span></span>-->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary pull-right" id="btnRenameThermostat"
                    onclick="renameThermostat()"><span data-translateid="btn_rename">Rename</span></button>
                <button type="button" class="btn btn-secondary pull-right" data-dismiss="modal"><span
                        data-translateid="btn_cancel">Cancel</span></button>
            </div>
        </div>
    </div>
</div>

<script>


    window.addEventListener("load", function load(event) {
        window.removeEventListener("load", load, false); //remove listener, no longer needed

        app.$renameThermostatModal = $('#renameThermostatModal');
        app.$renameThermostatInput = app.$renameThermostatModal.find('input');

        app.$renameThermostatModal.on("show.bs.modal", function () {

            var $fg = $('.form-group', $(this));
            $fg.removeClass('has-error');
            updateFeedbackIcon($fg);

            var $btn = $(".btn-primary", $(this));
            $btn.removeClass('disabled');

            var th = app.thermostats.get(app.session.thid);
            app.$renameThermostatInput.val(th.get('name'));
        });

        app.$renameThermostatModal.on("shown.bs.modal", function () {
            if (!navigator.userAgent.match(/iPhone|iPad/))
                app.$renameThermostatInput.focus();
        });

        app.$renameThermostatInput.on('keyup', function (e) {

            if (e.keyCode == 13) { // enter

                var $btn = $('.btn-primary', app.$renameThermostatModal);

                if ($btn.hasClass('disabled'))
                    return;

                this.blur(); // hide virtual keyboard
                $btn.click();
            }
        });
    }, false);

	/**
	 * Set groupname
	 *
	 * @memberof module:groups/functions
	 *
	 * @returns {void}
	 */
    function renameThermostat() {

        var $btn = $("#btnRenameThermostat");
        var s = app.sensors.get(app.session.thid);

        if (!s || $btn.hasClass('disabled')) {
            return;
        }

        var name = app.$renameThermostatInput.val().trim();
        if (s.get('name') !== name) {
            s.save({ name: app.$renameThermostatInput.val() }, { patch: true });
        }

        app.$renameThermostatInput.blur();
        app.$renameThermostatModal.modal('hide');
    }

   function verifyThermostatRename() {
		// common
		console.log('verify thermostat rename');

		var $parent = $(this).parent();
		var $errLine = $(".text-danger", $parent); //error-Text
		var $helpLine = $(".help-block", $parent);
		var val = $(this).val().trim();
		var errorText = '';

		$errLine.html('');

		// error test (1)
		//already exists?
		var doubles = [];
		if (app.thermostats) {
			doubles = app.thermostats.where({name: val});
		} else if (app.sensors) {
			doubles = app.sensors.where({name: val}).filter(s => s.get('id') !== app.session.thid);
		}

		if (app.thermostats) {
			if (doubles.length > 1 || (app.session.thid && doubles.length === 1 && doubles[0].id !== app.session.thid)) {

				$parent.addClass("has-error");

				errorText = '<span>';
				errorText = translate('error_nameExists').replace('{1}', val);
				errorText += '</span>';

				$errLine.html(errorText);
			} else {
				$parent.removeClass("has-error");
			}
		} else if (app.sensors) {
			if (doubles.length > 0) {
				$parent.addClass("has-error");

				errorText = '<span>';
				errorText = translate('error_nameExists').replace('{1}', val);
				errorText += '</span>';

				$errLine.html(errorText);
			} else {
				$parent.removeClass("has-error");
			}
		}


		// error test (2)
		// ...

		// common update feedback icon
		updateFeedbackIcon($parent);

		// enable create group button,
		// if input is valid and no error is shown
		var $btn = $(this).closest('.modal').find('.btn-primary');

		if (val.length > 0 && !$parent.hasClass("has-error")) {
			$btn.removeAttr("disabled");
		} else {
			$btn.attr("disabled", "disabled");
		}
	}
</script>