var taskViewApp = angular.module('taskViewApp', ['LoginService', 'tasksService', 'usersService', 'taskstatusesService', 'groupsService', 'checklist-model', 'tasktypesService', 'taskcommentsService', 'ngSanitize']).run(['$rootScope',
    function($rootScope) {
        $rootScope.scoped = {
            format: 'HH:mm:ss'
        };
        $rootScope.vm = {
            datetime: '05/13/2011 6:30 AM'
        }
    }
    ]);
taskViewApp.filter('propsFilter', function() { // root filter
    return function(items, props) {
        var out = [];
        if (angular.isArray(items)) {
            var keys = Object.keys(props);
            items.forEach(function(item) {
                var itemMatches = false;
                for (var i = 0; i < keys.length; i++) {
                    var prop = keys[i];
                    var text = props[prop].toLowerCase();
                    if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
                        itemMatches = true;
                        break;
                    }
                }
                if (itemMatches) {
                    out.push(item);
                }
            });
        } else {
            // Let the output be the input untouched
            out = items;
        }
        return out;
    };
});
taskViewApp.directive('ngEnter', function() { // event root enter
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
            if (event.which === 13) {
                scope.$apply(function() {
                    scope.$eval(attrs.ngEnter);
                });
                event.preventDefault();
            }
        });
    };
});
taskViewApp.directive('schrollBottom', function() { // scroll bottom
    return {
        scope: {
            schrollBottom: "="
        },
        link: function(scope, element) {
            scope.$watchCollection('schrollBottom', function(newValue) {
                if (newValue) {
                    $(element).scrollTop($(element)[0].scrollHeight);
                }
            });
        }
    }
});
taskViewApp.directive('dropZone', function() { // drop drag
    return function(scope, element, attrs) {
        element.dropzone({
            init: function() {
                this.on('addedfile', function(file) {
                    scope.dragfile(file);
                });
            }
        });
    }
});
taskViewApp.factory('taskView', function($timeout, $http, $window, $interval, Login, //
    Tasks, Users, Taskstatuses, Tasktypes, Taskcomments, Groups, $ionicLoading) {
    var paging = 30;
    var taskView = function() {
        this.currentIdLogin = '';
        this.currentUser = {};
        this.allUser = [];
        this.userMessage = [];
        this.typeTask = [];
        this.dataTask = [];
        this.dataTaskSearch = [];
        this.TaskById = [];
        this.dataSubTask = [];
        this.listSubTask = [];
        this.subComplete = [];
        this.detailTask = [];
        this.groupTask = [];
        this.userFollow = [];
        this.userAssign = {};
        this.historyTask = [];
        this.createId = '';
        this.ready = false;
        this.limitTo = 3;
        this.toHistory = 0;
        this.toAttached = 0;
        this.toComment = 0;
    };
    taskView.prototype = {
        init: function() {
            return this.checkLogin();
            // return this.getTypeTask();
        },
        realLogin: function() {
            var self = this;
            return Login.checkLogin().success(function(data) {
                console.log('realLogin', data);
                if (data.status == false) {
                    localStorage.setItem("login_status", "0");
                    redirectTo('index.html');
                } else {
                    self.currentIdLogin = parseInt(data.status.id);
                    self.currentUser = {
                        id: parseInt(data.status.id),
                        name: data.status.display_name,
                        imgprofile: data.status.image_pic,
                        email: data.status.email,
                        image_pic: data.status.image_pic
                    }
                    return self;
                }
            });
        },
        checkLogin: function() {
            var self = this;
            return Login.checkLogin().success(function(data) {
                // console.log('checkLogin',data);
                if (data.status == false) {
                    localStorage.setItem("login_status", "0");
                    redirectTo('index.html');
                } else {
                    self.currentIdLogin = parseInt(data.status.id);
                    self.currentUser = {
                        id: parseInt(data.status.id),
                        name: data.status.display_name,
                        imgprofile: data.status.image_pic,
                        email: data.status.email
                    }
                    self.getTypeTask();
                    return self;
                }
            });
        },
        getTypeTask: function() {
            var self = this;
            return Tasktypes.getSelect().success(function(data) {
                self.typeTask = _.each(data, function(val, index) {
                    val.name = String(val.name).toLowerCase();
                });
                self.getUser();
                return self;
            })
        },
        getUser: function() {
            var self = this;
            var _param = {
                rows: 'All',
                showUserStatus : 'active'
            }
            return Users.getPaging(_param).success(function(data) {
                _.each(data.data, function(val, index) {
                    nick_name = val.first_name + ' ' + val.last_name;
                    var _item = {
                        id: val.id,
                        screen_name: nick_name + ' - ' + val.positiontitles_name,
                        name: nick_name,
                        imgprofile: val.image_pic,
                        email: val.email
                    }
                    self.allUser.push(_item);
                });
                self.userMessage = self.allUser;
                // self.getdataTask();
                self.getdataTask(paging, paging, paging, paging, paging);
                return self;
            });
        },
        getdataTask: function(incompletepaging, upcomingpaging, followingpaging, downtimepaging, completepaging, search) {
            $ionicLoading.show({
                template: templateLoading
            });
            var self = this;
            return Tasks.getdataTask(currentIdLogin, incompletepaging, upcomingpaging, followingpaging, downtimepaging, completepaging, search).success(function(data) {
                if (!startpage) $ionicLoading.hide();
                // edit by haudao
                if (data.style == 'search') {
                    self.dataTaskSearch = data.data;
                    _.each(self.dataTaskSearch, function(val, index) {
                        _.extend(val, {
                            taskname: val.name,
                        });
                    });
                    self.ready = true;
                    return self;
                }
                // end edit

                var datareturn = data.data;
                // self.checknotifi = data.checknotifi;
                var task1 = arrayUnion(datareturn[0], datareturn[1], function(item1, item2) {
                    return item1.id == item2.id;
                });
                var task2 = arrayUnion(datareturn[2], datareturn[3], function(item1, item2) {
                    return item1.id == item2.id;
                });
                var task3 = arrayUnion(task1, task2, function(item1, item2) {
                    return item1.id == item2.id;
                });
                self.dataTask = arrayUnion(task3, datareturn[4], function(item1, item2) {
                    return item1.id == item2.id;
                });
                _.each(self.dataTask, function(val, index) {
                    if(val.taskdes!=null){
                        if(val.taskdes.length>270){
                            val.desShow = val.taskdes.substring(0,270)+'...';
                            val.seeMore = true;
                        }
                        else{
                            val.seeMore = false;
                        }
                    }
                    _.extend(val, {
                        taskname: val.name,
                    });
                });
                self.countTaskOfTask = data.countTaskOfTask;
                self.ready = true;
                return self;
            })
        },
        show: function(id, phoneApp) {
            // $ionicLoading.show({template: templateLoading });
            var self = this;
            return Tasks.show(id, phoneApp).success(function(data) {
                self.TaskById = data;
                self.ready = true;
                return self;

            })
        },
        loadMoreTask: function(action, paing) {
            var self = this;
            return Tasks.loadMoreTask(action, paing, currentIdLogin).success(function(data) {
                self.dataTask = data.data;
                self.tasktype_id = data.tasktype_id;
                self.row = data.row;
                self.checkloadmore = data.checkloadmore;
                _.each(self.dataTask, function(val, index) {
                    _.extend(val, {
                        taskname: val.name,
                    });
                });
                self.ready = true;
                return self;
            })
        },
        getListSubTask: function(task_id) {
            var self = this;
            return Tasks.getListSubTask(task_id).success(function(data) {
                self.dataSubTask = data.data;
                self.group_id = data.group_id;
                self.getSubComplete();
                return self;
            })
        },
        getSubComplete: function() {
            var self = this;
            self.subComplete = [];
            self.listSubTask = _.each(self.dataSubTask, function(val) {
                _.extend(val, {
                    taskname: val.name
                });
                val.type = String(val.type).toLowerCase();
                val.starttime = Date.parseDate(val.starttime);
                val.endtime = Date.parseDate(val.endtime);
                if (val.type == 'complete') {
                    self.subComplete.push(val.id);
                }
                if (val.ownerId == parseInt(self.currentIdLogin) || val.assignerId == parseInt(self.currentIdLogin)) {
                    _.extend(val, {
                        s_disable: 'n'
                    });
                } else {
                    _.extend(val, {
                        s_disable: 'y'
                    });
                }
            });
            return self;
        },
        makeSubComplete: function(sTask, checked) {
            var self = this;
            var idx = self.dataSubTask.indexOf(_.where(self.dataSubTask, {
                id: sTask.id
            })[0]);
            checked == true ? self.dataSubTask[idx].type = 'complete' : self.dataSubTask[idx].type = 'incomplete';
            self.getSubComplete();
            return self;
        },
        createTask: function(objParam) {
            $ionicLoading.show({
                template: templateLoading
            });
            var self = this;
            return Tasks.createTask(objParam, parseInt(self.currentIdLogin)).success(function(data) {
                if(data.status == false){
                    $cordovaToast.showLongCenter(data.msg);
                    return;
                }
                self.createId = data.id;
                return self;
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        },
        updateAssign: function($item, $model) {
            var self = this;
            $ionicLoading.show({
                template: templateLoading
            });
            return Tasks.updateassign($item, $model).success(function(data) {
                self.tasktype = data.tasktype;
                return self;
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        },
        deadlineTask: function(val_time, task_id) {
            var self = this;
            return Tasks.updatetask('', task_id, 'update endtime', '', val_time, conFig.fDatetoServer).success(function(data) {
                return self;
            })
        },
        dueTimeTask: function(start_time, end_time, task_id) {
            var self = this;
            return Tasks.updatetask('', task_id, 'update due time', start_time, end_time, conFig.fDatetoServer).success(function(data) {
                return self;
            })
        },
        messageTask: function(task_id, msg, type) {
            var self = this;
            // $ionicLoading.show({template: templateLoading });
            return Tasks.MessageTask(task_id, msg, self.currentIdLogin, type).success(function(data) {
                if(data.status == false){
                  $cordovaToast.showLongCenter(data.msg);
                  return;
              }
                // $ionicLoading.hide();
                self.createId = data.id;
                return self;
            })
        },
        removeFollow: function(user_id, task_id) {
            var self = this;
            $ionicLoading.show({
                template: templateLoading
            });
            return Tasks.updatetask(user_id, task_id, 'remove user follow', '', '', '').success(function(data) {
                // $ionicLoading.hide();
                return self;
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        },
        updateFollow: function(data_user, task_id, currentTask) {
            $ionicLoading.show({
                template: templateLoading
            });
            var self = this;
            return Tasks.updatetask(data_user, task_id, 'updatefollow', currentTask, '', '', self.currentIdLogin).success(function(data) {
                // $ionicLoading.hide();
                return self;
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Connection Error!!!');
            });
        },
        getMessage: function(task_id) {
            var self = this;
            $ionicLoading.show({
                template: templateLoading
            });
            return Taskcomments.show(task_id).success(function(data) {
                $ionicLoading.hide();
                self.detailTask = [];
                _.each(data, function(val, index) {
                    var iUser = _.where(self.userMessage, {
                        id: parseInt(val.user_id)
                    });
                    if (iUser.length > 0) {
                        var idetail = {
                            msgId: val.id,
                            id: iUser[0].id,
                            name: iUser[0].name,
                            imgprofile: iUser[0].imgprofile,
                            email: iUser[0].email,
                            type: val.type,
                            content: val.comments,
                            date: Date.parseDate(val.created_date),
                            dateView: moment(val.created_date,'YYYY-MM-DD HH:mm:ss').format('MM/DD/YYYY h:mm:ss a'),
                        }
                        self.detailTask.push(idetail);
                    }
                });
                self.detailTask.length - self.limitTo > 0 ? self.toComment = data.length - self.limitTo : self.toComment = 0;
                return self;
            })
        },
        changeType: function(type) {
            var self = this;
            return Tasks.changetype(type).success(function(data) {
                return self;
            })
        },
        createSubTask: function(task_id) {
            $ionicLoading.show({
                template: templateLoading
            });
            var self = this;
            return Tasks.createSubTask(task_id, parseInt(self.currentIdLogin)).success(function(data) {
                if(data.status == false){
                    $cordovaToast.showLongCenter(data.msg);
                    return false;
                }
                $ionicLoading.hide();
                self.createId = data;
                return self;
            })
        },
        getGroup: function() {
            var self = this;
            return Groups.getSelect().success(function(data) {
                self.groupTask = data;
                return self;
            })
        },
        getDataGroup: function(group_id) {
            $ionicLoading.show({
                template: templateLoading
            });
            var self = this;
            return Tasks.getDataGroup(group_id).success(function(data) {
                $ionicLoading.hide();
                self.userAssign = data.assige;
                self.userFollow = data.follow;
                if (parseInt(data.assige.id) == parseInt(self.currentUser)) {
                    self.userAssign = {};
                }
                self.userFollow = _.filter(data.follow, function(val) {
                    return parseInt(val.id) != parseInt(self.currentIdLogin);
                });
                return self;
            })
        },
        uploadFile: function(file) {
            var self = this;
            return Tasks.uploadfile(file).success(function(data) {
                return data;
            })
        },
        delAttached: function(task) {
            var self = this;
            $ionicLoading.show({
                template: templateLoading
            });
            return Tasks.delAttached(task).success(function(data) {
                $ionicLoading.hide();
                return data;
            })
        },
        sendMail: function(task_id, action) {
            var self = this;
            var url = url_site + '/tasks.html';
            return Tasks.sendmail(task_id, action, parseInt(self.currentIdLogin), url).success(function(data) {
                self.comments = data.comments;
                self.task_id = data.id;
                return self;
            }).error(function(data, status, headers, config) {
                $ionicLoading.hide();
                console.log('error status: ' + status);
                $cordovaToast.showLongTop('Can\'t send mail!!!');
            });
        },
        updateInputTask: function(_task) {
            var self = this;
            return Tasks.updateInputTask(_task).success(function(data) {
                return self;
            })
        },
        logOut: function(_task) {
            var self = this;
            return Login.logout().success(function(data) {
                return $window.location.href = url_login;
            })
        },
        createHistory: function(task_id, comments) {
            var self = this;
            return Tasks.createHistory(task_id, comments).success(function(data) {
                self.historyTask = data;
                data.length - self.limitTo > 0 ? self.toHistory = data.length - self.limitTo : self.toHistory = 0;
                return this;
            })
        },
        getHistory: function(task_id) {
            var self = this;
            return Tasks.getHistory(task_id).success(function(data) {
                $ionicLoading.hide();
                self.historyTask = data;
                data.length - self.limitTo > 0 ? self.toHistory = data.length - self.limitTo : self.toHistory = 0;
                return this;
            })
        },
        Reassign_task_group: function(task_id, group_id) {
            var self = this;
            return Tasks.Reassign_task_group(task_id, group_id).success(function(data) {
                self.Reassign_follow = data.follow;
                self.Reassign_assign = data.assign;
                return this;
            })
        }
    }
    return taskView;
})
