var rooms_pagesize = $('#rooms_pagesize');
angular.module('roomsCtrl', []).controller('roomsController', function($timeout,$cordovaToast, $ionicPopup, $ionicLoading, $scope, $http, $window,//
   $interval, Login, Rooms,$ionicScrollDelegate,$cordovaImagePicker,$cordovaFileTransfer) {
    $scope.currentPage = 1;
    withoutPopup_ROM = $scope;
    $scope.itemsPerPage = 200;
    $scope.entryLimit = $scope.itemsPerPage;
    $scope.searchRooms = {
        rows: $scope.itemsPerPage,
        current_page: $scope.currentPage,
        search: "",
        show_all: false
    };
    //role
    $scope.currentIdLogin = currentIdLogin;
    $scope.roleName = role;
    $scope.isAdmin = isAdmin;
    $scope.isManager = isManager;
    $scope.isReporter = isReporter;
    $scope.isScheduler = isScheduler;
    $scope.isFieldinstaller = isFieldinstaller;
    $scope.isSalesman = isSalesman;
    $scope.isWarehouse = isWarehouse;
    $scope.dispathRoomId = dispathRoomId;
    $scope.imageURI = '';
    /*$scope.getUsers = function(){
        User.get().success(function(data){
            $scope.users= data;
        });
    }
    $scope.getUsers();
    */
    $scope.getRooms = function() {
        $ionicLoading.show({
            template: templateLoading
        });
        Rooms.getPaging($scope.searchRooms).success(function(data) {
            $scope.rooms = data.data;
            $ionicLoading.hide();
            $scope.currentPage = data.page;
            $scope.itemsPerPage = $scope.searchRooms.rows;
            rooms_pagesize.val($scope.itemsPerPage);
            $scope.totalItems = data.total_rows;
        });
    };
    $scope.searchChanged = function() {
        $scope.getRooms();
    }
    $scope.ShowActive_ROM = function(show_all) {
        $scope.searchRooms.show_all = show_all;
        $scope.getRooms();
    }
        /*$scope.getSelectRooms = function(){
            Rooms.getSelect().success(function(data){
                $scope.selectRooms = data;
            });
        }
        $scope.getSelecRooms();*/
        /*
        xem demo upload file tai day:
        http://jsfiddle.net/danialfarid/1m6fn6re/
        $scope.upload = function (file) {
            Upload.upload({
                url: '/todo',
                fields: $scope.todoData,
                file: file
            }).progress(function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
            }).success(function (data, status, headers, config) {
                console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
            }).error(function (data, status, headers, config) {
                console.log('error status: ' + status);
            })
        };
        */
        $scope.sizeChanged = function() {
            $scope.searchRooms.rows = $scope.entryLimit;
            rooms_pagesize.val($scope.searchRooms.rows);
            localStorage.setItem('rooms_pagesize', $scope.searchRooms.rows);
            $scope.searchRooms.current_page = 1;
            $scope.getRooms();
        }
        $scope.pageChanged = function() {
            console.log($scope.currentPage);
            $scope.searchRooms.current_page = $scope.currentPage;
            $scope.getRooms();
        };
    // $scope.getRooms();
    $scope.setPage = function(pageNo) {
        $scope.currentPage = pageNo;
        console.log('doi page');
    };
    $scope.addRoomsData = {};
    $scope.addRoomsData.selectusers = [];

    $scope.createRooms = function(formValide,file) {
        if (formValide.$invalid || !$scope.addRoomsData.selectusers || $scope.addRoomsData.selectusers.length == 0) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        if (file == undefined || file == "" || file == null) {
            $cordovaToast.showLongTop('Please seletct image .!!!');
            return;
        }
        $scope.addRoomsData.selectusers = JSON.stringify($scope.addRoomsData.selectusers);
        var options = {
            fileName: file.substring(file.lastIndexOf('/') + 1),
            fileKey: "file",
            params: $scope.addRoomsData,
            mimeType: 'image/jpeg',
            chunkedMode: false
        };
        $ionicLoading.show({
            template: templateLoading
        });
        $cordovaFileTransfer.upload(url_server + 'rooms', file , options).then(function(e) {
            var results = JSON.parse(e.response);
            $ionicLoading.hide();
            if (results.status) {
                $cordovaToast.showLongTop(results.msg);
                $scope.closeTarget('#settingRoomManagementAdd');
                $scope.imageURI = '';
                $('#iconAddRoom').attr("src","");
                $scope.file = null;
                $scope.getRooms();
                $scope.initialUser = [];
                $scope.addRoomsData = {};
                $scope.addRoomsData.selectusers = [];
            } else {
                $cordovaToast.showLongTop(results.msg);
            }
        }, function(err) {
            $ionicLoading.hide();
            $cordovaToast.showLongTop('Connection Error!!!');
        }, function(progress) {
            //$cordovaToast.showLongTop(data.msg);
        });
    }

    $scope.editRoomsData = {};
    $scope.editRoomsData.selectusers = [];
    $scope.editRooms = function(id) {
        $scope.file = null;
        $scope.imageURI = '';
        $('#iconEditRoom').attr("src","");
        $scope.file = null;
        Rooms.show(id).success(function(data) {
            $scope.editRoomsData = data;
            $scope.editRoomsData.selectusers = data.users;
            delete $scope.editRoomsData.icon;
            var arr = [];
            $scope.editRoomsData.selectusers.forEach(function(item) {
                arr.push(item.id);
            });
            $scope.initialUserEdit = _.uniq(arr);
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
   
    $scope.updateRooms = function(formValide,file) {
        if (formValide.$invalid || !$scope.editRoomsData.selectusers || $scope.editRoomsData.selectusers.length == 0) {
            $cordovaToast.showLongTop('Please fill all the required information.!!!');
            return;
        }
        $ionicLoading.show({
            template: templateLoading
        });
        var id = $scope.editRoomsData.id;
        if(file!== null && file !== '' && file !== undefined){
            $scope.editRoomsData.selectusers = JSON.stringify($scope.editRoomsData.selectusers);
            var options = {
                fileName: file.substring(file.lastIndexOf('/') + 1),
                fileKey: "file",
                params: $scope.editRoomsData,
                mimeType: 'image/jpeg',
                chunkedMode: false
            };
            $cordovaFileTransfer.upload(url_server + 'settingrooms/' + id,file, options).then(function(e) {
                $ionicLoading.hide();
                var data = JSON.parse(e.response);
                if (data.status) {
                    $cordovaToast.showLongTop(data.msg);
                    $scope.closeTarget('#settingRoomManagementEdit');
                    $scope.imageURI = '';
                    $scope.getRooms();
                    $scope.initialUser = [];
                    $scope.editRoomsData = {};
                }
            }, function(err) {
                $ionicLoading.hide();
            }, function(progress) {
                $ionicLoading.show({
                    template: templateLoading
                });
            });
        }else{
            Rooms.update(id, $scope.editRoomsData).success(function(data) {
                if (data.status) {
                    $cordovaToast.showLongTop(data.msg);
                    $scope.closeTarget('#settingRoomManagementEdit');
                    $scope.getRooms();
                    $scope.initialUser = [];
                    $scope.editRoomsData = {};
                } else {
                    $cordovaToast.showLongTop(data.msg);
                }
            }).error(function (data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        } 
    }


    $scope.deleteRoomsData = {};
    $scope.confrimRooms = function(item) {
        $scope.deleteRoomsData = item;
    }
    $scope.deleteRooms = function() {
        var id=$scope.deleteRoomsData.id;
        $ionicLoading.show({
            template: templateLoading
        });
        Rooms.destroy(id).success(function(data) {
            $scope.closeTarget('#settingRoomManagementDelete');
            var idx = _.findLastIndex($scope.rooms, { id: id.toString() });
            $ionicLoading.hide();
            if (data.status) {
                $scope.rooms.splice(idx,1);
                $ionicScrollDelegate.$getByHandle('scrollRooms').resize();
                $cordovaToast.showLongTop(data.msg);
            } else {
                $cordovaToast.showLongTop(data.msg);
            }
        }).error(function (data, status, headers, config) {
            $ionicLoading.hide();
            console.log('error status: ' + status);
            $cordovaToast.showLongTop('Connection Error!!!');
        });
    }
    $scope.getUserLogin = function() {
        return Login.getUserLogin().success(function(data) {
            if (data == false) {
                $scope.displayname = "Profile";
            } else {
                $scope.imagePath = pathToPublic + data.image_pic;
                var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
                if ($.trim(displayname) == "") {
                    $scope.displayname = "Hello, " + data.email;
                } else {
                    $scope.displayname = "Hello, " + displayname;
                }
            }
        });
    }
    // $scope.getUserLogin();
    $scope.logout = function() {
        return Login.logout().success(function(data) {
            $window.location.href = url_login;
        });
    }
    $scope.checkLogin = function() {
        return Login.checkLogin().success(function(data) {
            if (data.status == false) {
                $window.location.href = url_login;
            }
        });
    }
    // edit by haudao
    $scope.infoRooms = {};
    $scope.openPopupRoomsOption = function(id) {
        $scope.infoRooms.id = parseInt(id);
        $scope.editRooms(id);
        appDialogToggle('open', '#popupSettingRoomOption')
    }
    $scope.autocompleteList = {};
    $scope.filterUser = function(query, style) {
        var returnValue = {
            items: []
        };
        var listIdArray = style == 'add' ? $scope.autocompleteList.refferedUserAdd : $scope.autocompleteList.refferedUserEdit;
        $scope.allUser.forEach(function(item) {
            if (listIdArray.indexOf(item.id) < 0) {

                if (item.screen_name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
                    returnValue.items.push(item);
                } else if (item.id.toString().indexOf(query) > -1) {
                    returnValue.items.push(item);
                }

            }
        });
        return returnValue;
    };
    $scope.initialUser = [];
    $scope.initialUserEdit = [];
    $scope.setValueForUser = function(modelValue) {
        for (var i = 0; i < $scope.allUser.length; i++) {
            // console.log($scope.allUser[i].id,modelValue)
            if ($scope.allUser[i].id == modelValue) {
                // data={id:$scope.rootSupplieritems[i].id,name:$scope.rootSupplieritems[i].name};
                return $scope.allUser[i];
            }
        }
        return {};
    };
    $scope.onSelectUser = function(callback, style) {
        if (style == 'add') {
            if ($scope.addRoomsData.selectusers.indexOf(callback.item) < 0) $scope.addRoomsData.selectusers.push(callback.item);
        } else {
            var index = _.findIndex($scope.editRoomsData.selectusers, {
                id: callback.item.id.toString()
            });
            if (index < 0) $scope.editRoomsData.selectusers.push(callback.item);
            // console.log($scope.editRoomsData.selectusers);
        }

    }
    $scope.openPickerForProfile = function () {
        var options = {
            maximumImagesCount: 1,
            width: 0,
            height: 0,
            quality: 100
        };
        $ionicLoading.show({template: templateLoading});
        $cordovaImagePicker.getPictures(options).then(function (results) {
            $scope.file = results[0];
            window.plugins.Base64.encodeFile($scope.file, function (base64) {
                $scope.imageURI = base64;
            });
            $timeout(function () {
                $ionicLoading.hide();
            }, 3000)
        })
    }

    $scope.setIndexViewOptionRoom = function(index){
        $scope.index_option_room=index;
        $timeout( function(){
            $('#btn-view-option-room-'+index).next('.quick-popup').addClass('show');
        }, 100);
    }

    $scope.onRemoveUser = function(callback, style) {
        if (style == 'add') {
            var index = $scope.addRoomsData.selectusers.indexOf(callback.item);
            $scope.addRoomsData.selectusers.splice(index, 1);
        } else {
            var index = _.findIndex($scope.editRoomsData.selectusers, {
                id: callback.item.id.toString()
            });
            if (index >= 0) $scope.editRoomsData.selectusers.splice(index, 1);
                // console.log($scope.editRoomsData.selectusers);
            }
        }
        // end edit
    })
