angular
    .module('universal')
    .directive('uniGrid', ["$templateCache", '$timeout', '$compile', '$templateRequest', '$http','$q',
        function ($templateCache, $timeout, $compile, $templateRequest, $http, $q) {
            return {
                require: [],
                scope: {
                    id: '@',
                    select:"="
                },
                template: '<div class="text-right" style="padding:3px;">'
                                        +'<input type="text" ng-model="filterText" />'
                                        +'<button ng-click="clickFilter()" type="button">найти</button>'
                                    +'</div><div style="height:150px;" ui-grid="gridOptions" ui-grid-edit ui-grid-row-edit ui-grid-resize-columns ui-grid-cellnav ui-grid-expandable class="grid"></div>',
                restrict: 'E',
                link: function ($scope, element, attrs, controllers) {
                    $scope.filterText = "";
                    $scope.gridOptions = {
                        //This is the template that will be used to render subgrid.
                        expandableRowTemplate: '../../scripts/expandableRowTemplate.html',
                        //This will be the height of the subgrid
                        //expandableRowHeight: 150,
                        //Variables of object expandableScope will be available in the scope of the expanded subgrid
                        //expandableRowScope: {
                        //    Warrents: undefined
                        //}
                    };
                    $scope.clickFilter = function () {
                        $scope.loadData();
                    }
                    $scope.gridOptions.enableCellEditOnFocus = true;
                    $scope.gridOptions.columnDefs = [{
                        name: "_new_",
                        displayName:"",
                        enableCellEdit: false ,
                        width: 20
                    }];
                    $scope.fields = [];
                    $scope.gridOptions.data = [];
                    $scope.delete = function (e, row) {
                        // удаляем
                        $http.post("/sources/" + $scope.id + "/delete/" + row.entity.ID, {}).then(function (response) {
                            $scope.loadData()
                        })
                    };

                    $http.post("/sources/" + $scope.id + "/fields/", {}).then(function (response) {
                        $scope.fields = response.data;
                        angular.forEach(response.data, function (value, key) {
                            if (value.FieldType != 6) {
                                var o = {
                                    name: value.Name,
                                    visible: value.Name != "ID",
                                    enableCellEdit: true,
                                    enableCellEditOnFocus: true,
                                    displayName: value.DisplayName ? value.DisplayName : value.Name,
                                    width: 200
                                };
                                if (value.TypeName == "System.DateTime") {
                                    o.type = 'date'
                                    o.cellFilter = "date:'dd.MM.yyyy': 'UTC+0300'"
                                }
                                if (value.TypeName == "System.Boolean") {
                                    o.type = 'boolean';
                                    o.cellTemplate = '<input type="checkbox" ng-click="grid.appScope.alert($event, row)" ng-model="row.entity.' + value.Name + '">'
                                }
                                if (value.Name == "WorkMode") {
                                    //  o.cellTemplate = '<select ng-model="row.entity.WorkMode"><option value="Вкл">Вкл</option><option value="Выкл">Выкл</option><option value="Авто">Авто</option></select>'
                                    o.editableCellTemplate = 'ui-grid/dropdownEditor'
                                    o.cellFilter = 'mapGender'
                                    o.editDropdownValueLabel = 'gender'
                                    o.editDropdownOptionsArray = [
                                        { id: 'Вкл', gender: 'Вкл' },
                                        { id: 'Выкл', gender: 'Выкл' },
                                        { id: "Авто", gender: "Авто" }
                                    ]
                                    //o.enableCellEdit = false
                                    //o.enableCellEditOnFocus = false
                                }
                                if (value.Name == "List" && value.TypeName == "List") {
                                    o.cellTemplate = "<a href='/raitings/SourceItem/{{::row.entity.ID}}'>...</a>"
                                    o.enableCellEdit = false
                                }
                                $scope.gridOptions.columnDefs.push(o);
                            }
                        });

                        $scope.gridOptions.columnDefs.push({
                            name: 'Action',
                            displayName: "Действия",
                            cellEditableCondition: false,
                            cellTemplate: '<div class="ui-grid-cell-contents ng-binding ng-scope" style="width:33px;"><a ng-show="row.entity._new_!=\'+\'" class="btn btn-danger btn-xs btn-block" ng-click="grid.appScope.delete($event, row)"><span class="glyphicon glyphicon-trash"></span></button></div>'
                        })
                        $timeout(function () {
                            $scope.loadData();
                        })
                    });

                    $scope.alert = function (e, row) {
                        $scope.saveRow(row.entity);
                    };

                    $scope.saveRow = function (rowEntity) {
                        angular.forEach($scope.fields, function (value, key) {
                            if (value.FieldType == 4 && rowEntity[value.Name] != null) {
                                if (Object.prototype.toString.call(rowEntity[value.Name]) === '[object Date]') {
                                    rowEntity[value.Name] = moment(rowEntity[value.Name]).format('DD.MM.YYYY')
                                }
                            }
                        })
                        var promise = $q.defer();
                        $scope.gridApi.rowEdit.setSavePromise(rowEntity, promise.promise);
                        promise.resolve();
                        if (rowEntity._new_ == "+") {
                            // добавляем
                            rowEntity._new_ = "";
                            console.log(rowEntity)
                            $http.post("/sources/" + $scope.id + "/add/", rowEntity).then(function (response) {
                                $scope.loadData()
                            })
                        } else {
                            console.log(rowEntity)
                            // сохраняем
                            $http.post("/sources/" + $scope.id + "/edit/" + rowEntity["ID"], rowEntity).then(function (response) {
                                $scope.loadData()
                            })                 
                            
                            
                        }                        
                    };

                    $scope.$on('someEvent', function (e, scope2) {
                        console.log("remove " + $scope.id)
                        scope2.$destroy();
                    });

                    $scope.selecter = function (i) {
                        //$scope.select = i;
                        for (var i = 0; i < $scope.scopes.length; i++) {
                            console.log($scope.scopes[i])
                            $scope.scopes[i].core.refresh();
                        }
                        $scope.$apply()
                    };

                    $scope.scopes = [];

                    $scope.gridOptions.onRegisterApi = function (gridApi) {
                        //set gridApi on scope
                        $scope.gridApi = gridApi;
                        gridApi.rowEdit.on.saveRow($scope, $scope.saveRow);
                        gridApi.cellNav.on.navigate(null, function (newRowCol, oldRowCol) {
                            for (var i = 0; i < $scope.scopes.length; i++) {
                                
                                $scope.$broadcast('someEvent', $scope.scopes[i]);
                               
                            }
                            $scope.scopes = [];
                            angular.forEach($scope.fields, function (value, key) {
                                if (newRowCol.row.entity["_new_"] == "+") {
                                    $scope.select = -1
                                    var el = angular.element(document.querySelector("#source_" + value.Name + "_" + $scope.id))
                                    el.empty();
                                } else {
                                    if (value.FieldType == 6) {

                                        var el = angular.element(document.querySelector("#source_" + value.Name + "_" + $scope.id))
                                        el.empty();
                                        var scope = $scope.$new();
                                        $scope.scopes.push(scope);
                                        
                                        el.append($compile("<uni-grid id='" + newRowCol.row.entity[value.Name] + "'></uni-grid>")(scope))
                                        if ($scope.select == -1)
                                            $scope.select = 0;

                                        //$("#source_" + value.Name + "_" + $scope.id).show()
                                        //$("#tab_" + value.Name + "_" + $scope.id).addClass("active");
                                    }
                                }
                            })
                            
                            //vm.gridApi.core.notifyDataChange(vm.gridApi.grid, uiGridConstants.dataChange.COLUMN);
                        });
                    };

                    $scope.loadData = function () {
                        $http.post("/sources/" + $scope.id + "/data/?searchText=" + $scope.filterText, {}).then(function (response) {
                            $scope.gridOptions.data = [];
                            angular.forEach(response.data, function (value, key) {
                                angular.forEach($scope.fields, function (value2, key2) {
                                    if (value2.FieldType == 4 && value[value2.Name] != null) {
                                        var s = new Date(parseInt(value[value2.Name].replace("/Date(", "").replace(")/", ""), 10));
                                        value[value2.Name] = moment(s).format("DD.MM.YYYY")
                                    }
                                })
                                $scope.gridOptions.data.push(value)
                            })


                            $scope.gridOptions.data.push({ _new_: "+" });

                            console.warn($scope.gridOptions.data);

                            $scope.gridApi.core.refreshRows()
                        })
                    };

                    $scope.$watch("select", function (newValue, oldValue) {
                        if (newValue != oldValue) {

                            if (newValue == -1 || oldValue == -1)
                                return;

                            $scope.id = newValue;
                            $scope.loadData();
                        }
                    });

                }
            }
        }])