'use strict';

/* Controllers */

function IndexCtrl($scope, $http) {
    $http.get('/api/posts').
            success(function (data, status, headers, config) {
                $scope.posts = data.posts;
            });
}

function AddPostCtrl($scope, $http, $location) {
    $scope.form = {};
    $scope.submitPost = function () {
        $http.post('/api/post', $scope.form).
                success(function (data) {
                    $location.path('/');
                });
    };
}

function ReadPostCtrl($scope, $http, $routeParams) {
    $http.get('/api/post/' + $routeParams.id).
            success(function (data) {
                $scope.post = data.post;
            });
}

function EditPostCtrl($scope, $http, $location, $routeParams) {
    $scope.form = {};
    $http.get('/api/post/' + $routeParams.id).
            success(function (data) {
                $scope.form = data.post;
            });

    $scope.editPost = function () {
        $http.put('/api/post/' + $routeParams.id, $scope.form).
                success(function (data) {
                    $location.url('/readPost/' + $routeParams.id);
                });
    };
}

function DeletePostCtrl($scope, $http, $location, $routeParams) {
    $http.get('/api/post/' + $routeParams.id).
            success(function (data) {
                $scope.post = data.post;
            });

    $scope.deletePost = function () {
        $http.delete('/api/post/' + $routeParams.id).
                success(function (data) {
                    $location.url('/');
                });
    };

    $scope.home = function () {
        $location.url('/');
    };
}

function LoginCtrl($scope, $http, $location, $routeParams) {

}

function RegisterCtrl($scope, $http, $location, $routeParams) {

    $scope.people = [
        {id: 1, role: 'Admin', actor: 'Administrator'},
        {id: 2, role: 'Configurator', actor: 'Configurator'},
        {id: 3, role: 'User', actor: 'Defual is user'}
    ];

    $scope.disabledUser = false;
    $scope.item = $scope.people[2]; // red
    $scope.update = function () {

        if ($scope.item.role === 'Admin')
        {
            $scope.selectedUsername = $scope.item.role;
            $scope.disabledUser = true;
        }
    };
}
function ChangePassCtrl($scope, $http, $location, $routeParams) {


}
function AccountCtrl($scope, $http, $location, $routeParams) {

    /* $http.post('/api/account').
     success(function (data, status, headers, config) {
     $scope.accounts = data.accounts;
     });
     */
}
function LogoutCtrl($scope, $http, $location, $routeParams) {

    $scope.logoutPost = function () {
        $http.delete('/api/logout').
                success(function (data) {
                    $location.url('/');
                });
    }
}
function ScalesCtrl($scope, $http, $location, $routeParams) {

    var localData = {invoice_number: 10,
        lincense: "licabc123",
        tax: 13.00,
        customer_name: "xyz",
        web_link: "Abc COm.",
        address1: "1 Infinite Loop",
        address2: "Cupertino, California, US",
        postal: "90210"

    };

    $scope.myData = [];

    function saveContributor(contributor) {
        $http.post('/scales/update', contributor).success(function () {

            console.log('SAVE success !!!!');
        }).error(function () {
            console.log('SAVE Error !!!!');

        });
    }

    $scope.gridOptions = {data: 'myData'};
    $scope.mySelections = [];

    $scope.refresh = function () {
        var url = "/scales/post";
        $http.post(url).success(function (data) {



            if (data.length)
            {
                $scope.myData = data;
            }

        }).error(function (error) {
            alert("Failed to get the Item from table" + url);
        });

        /*
         if ($scope.myData.length == 0)
         {
         var url = "/scales/new";
         $http.put(url, localData).success(function (savedTodo) {
         
         $scope.myData.push(savedTodo);
         
         alert(JSON.stringify(savedTodo));
         
         return;
         }).error(function (error) {
         alert("Failed to save the new Item");
         });
        
         }
         */

    };

    $scope.refresh();


    $scope.$on('ngGridEventEndCellEdit', function (evt) {

        // Detect changes and send entity to REST server

        saveContributor(evt.targetScope.row.entity);

    });

    $scope.pagingOptions = {
        pageSizes: [5, 10, 20],
        pageSize: 5,
        currentPage: 1
    };

    $scope.gridOptions = {
        data: 'myData',
        showFilter: true,
        showColumnMenu: true,
        enableCellSelection: true,
        enableCellEdit: true,
        showSelectionCheckbox: true,
        selectWithCheckboxOnly: true,
        enableColumnResize: true,
        enableHighlighting: true,
        selectedItems: $scope.mySelections,
        showFooter: true,
        columnDefs: [{field: 'invoice_number', displayName: 'invoice'},
            {field: 'lincense', displayName: 'lincense'},
            {field: 'tax', displayName: 'tax%'},
            {field: 'customer_name', displayName: 'customer_name'},
            {field: 'web_link', displayName: 'web_link'},
            {field: 'address1', displayName: 'address1'},
            {field: 'address2', displayName: 'address2'},
            {field: 'postal', displayName: 'postal'}
        ]
    };


    $scope.addItem = function () {

        var url = "/scales/new";
        localData.invoice_number = $scope.myData.length;
        $http.put(url, localData).success(function (savedTodo) {

            $scope.myData.push(savedTodo);

        }).error(function (error) {
            alert("Failed to save the new Item");
        });


    };
    $scope.allItems = function () {
        var dataLength = $scope.myData.length;
        alert($scope.myData[dataLength - 1].name);
    };


    $scope.remove = function () {
        if (!$scope.mySelections.length)
        {
            alert('Please slelect a row in grid');
            return;
        }

        angular.forEach($scope.mySelections, function (rowItem) {

            var del = $scope.myData.indexOf(rowItem);


            var contributor = $scope.myData[del];
            $http.post('/scales/delete', contributor).success(function () {
                console.log('delete success !!!!');

                $scope.gridOptions.selectRow(del, false);
                $scope.myData.splice($scope.myData.indexOf(rowItem), 1);

            }).error(function () {

                console.log('delete Error !!!!');

            });

        });
    };

}

function SiteCtrl($scope, $http, $location, $routeParams) {


    var MyList = 
        {
            "id": "1",
            "title": "RevealSystem",
            "dragdrop":"data-nodrag",
            "items": [
                {
                    "id": "2",
                    "add":true,
                    "title": "Servers",
                    "items":[
                       
                    ]
                }
            ]
        };
    
     $scope.list = [];

    var url = "/site/post";
    $http.post(url).success(function (data) {

        if (data.length)
        {
            $scope.list = data;
        }
        else
        {
            var url = "/site/new";

            $http.put(url, MyList).success(function (savedTodo) {
                
                $scope.list.push(savedTodo)

            }).error(function (error) {
                alert("Failed to save the new Item");
            });

        }
      

    }).error(function (error) {
        alert("Failed to get the Item from table" + url);
     

    });


     
    $scope.events = 'Events Message';
    
    //$scope.options = { };
    
    $scope.saveit= function() {
        
        $http.post('/site/update', $scope.list[0]).success(function () {

            console.log('SAVE success !!!!');
        }).error(function () {
            console.log('SAVE Error !!!!');

        });
        
    };
    
    $scope.removeSubItem = function(scope) {
        
        scope.remove();

        $scope.saveit();
 
    };
    
    $scope.newSubItem = function(scope) {

        var nodeData = scope.$modelValue;
        
        
       var serverid =  {
        id: nodeData.id * 10 + nodeData.items.length,
        title: nodeData.title + '.' + (nodeData.items.length + 1),
        ip:"localhost",
        edit:true,
        items: []
        };
        
        nodeData.items.push(serverid);
            $scope.saveit();
        serverid.editing = true;
    };
    
    $scope.editSubItem = function(scope) {
        
        var nodeData = scope.$modelValue;
        nodeData.editing = true;
        
    };
    
   $scope.saveSubItem = function(scope) {

        var nodeData = scope.$modelValue;
        nodeData.editing = false;
        
        
            $scope.saveit();
        
    };

    $scope.options = {
        dropped: function (event) {
            var node = event.source.nodeScope.$modelValue;
            console.log(event.dest.nodesScope.$parent.$modelValue);
            var parent = event.dest.nodesScope.$parent.$modelValue;
            $scope.events = 'Nó ' + node.title + (parent ? ' agora é filho de ' + parent.title : '');
        }
    };

}