/* exmample usage, you can also use ng-value as well to access scope fields
<div>
                    <label>
                        <tic-radio-button ng-model="vm.color.name" value="red">
                        Red
                        </tic-radio-button>
                    </label><br/>
                    <label>
                        <tic-radio-button ng-model="vm.color.name" value="green">
                        Green
                        </tic-radio-button>
                    </label><br/>
                    <label>
                        <tic-radio-button ng-model="vm.color.name" value="blue">
                        Blue
                        </tic-radio-button>
                    </label><br/>
                    <tt>color = {{vm.color.name | json}}</tt><br/>
                </div>
                */
(function () {
    'use strict';
    angular.module('ti_common').directive('ticRadioButton', radioButton);
    radioButton.$inject = [];
    function radioButton() {
        return {
            restrict: 'E',
            scope: true,
            require: 'ngModel',
            compile: function (element) {
                var htmlText = '<span class="tic-radio-button"><i class="material-icons tic-radio-button">{{getIcon()}}</i>' + element.html() + '</span>';
                element.replaceWith(htmlText);
                return {
                    pre: function () { },
                    post: function (scope, element, attrs, modelCtrl) {
                        var value = attrs.value;
                        scope.getIcon = function () {
                            var isChecked = element.prop('checked');
                            if (isChecked) {
                                return 'radio_button_checked';
                            }
                            else {
                                return 'radio_button_unchecked';
                            }
                        };
                        // Bind the onChange event to update children
                        element.bind('click', function () {
                            scope.$apply(function () {
                                element.prop('checked', true);
                                modelCtrl.$setViewValue(value);
                            });
                        });
                        scope.$watch(function () {
                            return modelCtrl.$modelValue;
                        }, function (newValue) {
                            if (newValue === value) {
                                element.prop('checked', true);
                            }
                            else {
                                element.prop('checked', false);
                            }
                        }, true);
                    }
                };
            }
        };
    }
}());
