crmApp.service('GeneralService', function ($timeout, $q, $filter, localStorageService, TaskSI, AdvanceRulesService) {
    var _emailValidation = /^(([\w-'\.\-\+?]+)@([\w\.-]+)((\.(\w){1,9})+)(\s+)?((;(\s+)?)|$))+$/;
     //var _multipleEmailValidation = /^(([\w\.\-]+)@([\w\-]+)((\.(\w){1,9})+)(\s+)?((;(\s+)?)|$))+$/;
	var _multipleEmailValidation = /^(([\w\.\-\+?]+)@([\w\.-]+)((\.(\w){1,9})+)(\s+)?((;(\s+)?)|$))+$/;
    var _decimalValidation = /^[1-9]\d*(\,.\d+)?$/;
    var _phoneValidation = /^[0-9 -]*$/;
    var _phoneValidationMsg = "Format no. telefon tidak sah";
    var _emailValidationMsg = "Format alamat emel tidak sah";
    var _decimalValidationMsg = "Format tidak sah";
    var _multipleEmailValidationMsg = "Invalid email format. Please use ; for multiple emails";
    //var _integerValidation = /^\d{0,32}$/;
    //var _integerValidationMsg = "Invalid format";
    var _yearValidation = /^[1-2]{1,1}[0-9]{3,3}$/;
    var _yearValidationMsg = "Tahun tidak sah";
    //var _moneyValidation = /^((?!0(?!\.))\d{1,3}(,\d{3})*(\.[0-9]{2})?)$|^([0-9]{1,22}(\.[0-9]{2})?)$/;
    var _moneyValidation =           /^((?!0(?!\.))\d*(,\d*)*(\.[0-9]{0,2})?)$|^([0-9]{1,22}(\.[0-9]{0,2})?)$/; // decimal (16,2)
    var _moneyValidation15 =         /^((?!0(?!\.))\d*(,\d*)*(\.[0-9]{0,2})?)$|^([0-9]{1,20}(\.[0-9]{0,2})?)$/; // decimal(15, 2)
    var _moneyValidation15AllowNeg = /^((?!0(?!\.))\d*(,\d*)*(\.[0-9]{0,2})?)$|^([0-9]{1,20}(\.[0-9]{0,2})?)$|^-((?!0(?!\.))\d*(,\d*)*(\.[0-9]{0,2})?)$|^([0-9]{1,21}(\.[0-9]{0,2})?)$/; // decimal(15, 2)
    var _moneyValidationWithNeg = /^((?!0(?!\.))\d*(,\d*)*(\.[0-9]{0,2})?)$|^([0-9]{1,22}(\.[0-9]{0,2})?)$|^-((?!0(?!\.))\d*(,\d*)*(\.[0-9]{0,2})?)$|^([0-9]{1,22}(\.[0-9]{0,2})?)$/; // decimal(15, 2)
    var _moneyValidationMsg = "Input tidak sah atau nombor melebihi format yang dibenarkan";
    var _title = "Profil Dikemaskini!";
    var _text = "Maklumat profil berjaya dikemaskini.";
    var _refreshPageMsg = "Update conflict! Please refresh the page to proceed.";
    var isManager = false;

    var _outboundNew = 27;
    var _outboundReject = 28;
    var _outboundSchedule = 29;
    var _outboundInQueue = 30;
    var _outboundCalled = 31;
    var _outboundToUpdate = 32;
    var _outboundClosed = 33;

    var vm = this;
    this.Validation = {
        get Email() {
            return _emailValidation;
        },
        get EmailMsg() {
            return _emailValidationMsg;
        },
        get MultipleEmail() {
            return _multipleEmailValidation;
        },
        get MultipleEmailMsg() {
            return _multipleEmailValidationMsg;
        },
        get Phone() {
            return _phoneValidation;
        },
        get PhoneMsg() {
            return _phoneValidationMsg;
        },
        get Decimal() {
            return _decimalValidation;
        },
        get DecimalMsg() {
            return _decimalValidationMsg;
        },
        //get Integer() {
        //    return _integerValidation;
        //},
        //get IntegerMsg() {
        //    return _integerValidationMsg;
        //},
        get Year() {
            return _yearValidation;
        },
        get YearMsg() {
            return _yearValidationMsg;
        },
        get Money() {
            return _moneyValidation;
        },
        get Money15() {
            return _moneyValidation15;
        },
        get Money15AllowNeg() {
            return _moneyValidation15AllowNeg;
        },
        get MoneyWithNeg() {
            return _moneyValidationWithNeg;
        },
        get MoneyMsg() {
            return _moneyValidationMsg;
        }
    };

    this.SaveMessage = {
        get Title() {
            return _title;
        },
        get Text() {
            return _text;
        }
    };

    this.ErrorHandling = {
        get RefreshPageMsg() {
            return _refreshPageMsg;
        }        
    };

    this.OutboundStatus = {
        get New() {
            return _outboundNew;
        },
        get Reject() {
            return _outboundReject;
        },
        get InQueue() {
            return _outboundInQueue;
        },
        get Called() {
            return _outboundCalled;
        },
        get ReadyToUpdate() {
            return _outboundToUpdate;
        },
        get Closed() {
            return _outboundClosed;
        }
    }

    //Advance Rule:  Validation
    vm.validateAdvancedRules = function (isOutbound) {
        if (isOutbound == undefined) isOutbound = false;
        var isValid = true;
        var isRequredJenisKempen = false;
        var errMessage = "";
        var errOutboundMessage = "Jenis Kempen field is mandatory for advanced rules.";
        var _AdvanceRules = AdvanceRulesService.getList();
        var checkForOutbound = isOutbound;

        angular.forEach(_AdvanceRules, function (rules, key) {
            if (isValid) {
                var invalidRulesField = $filter('filter')(rules.RuleGroup, { DisplayField: null });
                //var invalidRulesOperator = $filter('filter')(rules.RuleGroup, { FieldOperator: null });

                var invalidRulesOperator = $filter('filter')(rules.RuleGroup, function (item) {
                    if (item.FieldOperator == undefined || item.FieldOperator == null || item.FieldOperator == '' || item.FieldOperator == '0') {
                        isValid = false;
                    }
                });


                var hasFieldValue = true;
                angular.forEach(rules.RuleGroup, function (rulesGroup, key) {
                    var rulesValue = $filter('filter')(rulesGroup.FieldValues, function (item) {
                        if (item.FieldValue == undefined || item.FieldValue == null || item.FieldValue == '') {
                            isValid = false;
                            return item;
                        }
                    });
                    if (rulesGroup.FieldValues.length == 0 || (rulesValue != undefined && rulesValue.length > 0)) {
                        isValid = false;
                    }
                });

                if ((invalidRulesField != undefined && invalidRulesOperator.length > 0) ||
                      (invalidRulesOperator != undefined && invalidRulesOperator.length > 0)) {
                    isValid = false;
                }
            }
        });

        if (!isValid) { errMessage = "Please fill in all mandatory fields."; }

        if (checkForOutbound) {
            var jenisKempenCount = 0;
            angular.forEach(_AdvanceRules, function (rules, key) {

                var rulesJenisKempen = $filter('filter')(rules.RuleGroup, { FieldMapping: 'JenisKempenID' });

                jenisKempenCount += rulesJenisKempen.length;
                //if (rulesJenisKempen.length == 0) {
                //    isValid = false;
                //    isRequredJenisKempen = true;
                //    errMessage += ' ' + errOutboundMessage;
                //} else if (rulesJenisKempen.length > 0) {
                //    // avoid outbound specific checking after found
                //    checkForOutbound = false;
                //}                     
            });

            if (jenisKempenCount == 0) {
                isValid = false;
                errMessage += ' ' + errOutboundMessage;
            }

        }

        if (!isValid) {
            swal({
                title: errMessage,
                text: "",
                type: "warning",
                timer: 2500
            });
        }
        return isValid;
    }


    function callUserProfile() {
        var deferred = $q.defer();

        if (localStorage.getItem("crmApp.UserInfo") === null) {
            TaskSI.getLoginInfo().then(function (resp) {
                if (resp.status === 200) {
                    deferred.resolve(resp.data);

                    console.log('-----Get Initial Login Info-----')
                    console.log(resp.data);
                }
            });
        }
        else {
            console.log('-----Get Stored Login Info-----');
            objUser = localStorageService.get('UserInfo');

            deferred.resolve(objUser);
        }
        return deferred.promise;
    }

    vm.getUserProfile = function () {
        var deferred = $q.defer();
        var objUser = null;

        callUserProfile().then(function (r) {

            localStorageService.set('UserInfo', r);
            objUser = localStorageService.get('UserInfo');
            console.log('Set local storage');
            console.log(objUser);
            deferred.resolve(objUser);
        });
        return deferred.promise;

    };

    function callUserProfileServer() {
        var deferred = $q.defer();
        TaskSI.getLoginInfo().then(function (resp) {
            if (resp.status === 200) {
                deferred.resolve(resp.data);

                console.log(resp.data);
            }
        });
        return deferred.promise;
    }

    //vm.getUserProfile = function () {
    //    return new Promise((resolve, reject) => {

    //            var objUser = null;

    //            if (localStorage.getItem("crmApp.UserInfo") === null) {
    //                TaskSI.getLoginInfo().then(function (r) {

    //                    if (r.status === 200) {
    //                        //localStorageService.clearAll();
    //                        localStorageService.set('UserInfo', r.data);
    //                        objUser = localStorageService.get('UserInfo');
    //                        console.log('-----Get Initial Login Info-----');

    //                        console.log(objUser);
    //                    }

    //                });
    //            } else {
    //                var deferred = $q.defer();
    //                deferred.reject('');
    //                objUser = deferred.promise;
    //                console.log('-----Get Stored Login Info-----');
    //                objUser = localStorageService.get('UserInfo');
    //                console.log(objUser);
    //            }

    //            console.log(objUser);
    //            resolve(objUser);

    //    })
    //};


    this.checkCurrentUserRole = function (d) {
        //var userRoles = $scope.UserInfo.RoleGroups;
        var isValid = false;
        if (localStorage.getItem("crmApp.UserInfo") === null) {

            console.log("1.1a");
            vm.getUserProfile().then(function (r) {
                isValid = this.checkRole(r, d);
            });
        }
        else {
            console.log("1.1b");
            objUser = localStorageService.get('UserInfo');
            isValid = this.checkRole(objUser, d);
            console.log(isValid);
        }
        return isValid;
    };

    this.checkRole = function (oUser, d) {
        var isValid = false;

        console.log("1.2");
        console.log(oUser);
        //var a = $filter('filter')(userRoles, { FunctionalRoleID: d }, true);
        if (oUser != undefined) {
            angular.forEach(oUser.RoleGroups, function (value, key) {
                if (d == value.FunctionalRoleID) {

                    isValid = true;
                }
            });
        }

        return isValid;
    };

    this.daysBetween = function (start, end) {
        var dtStart = moment(start, "YYYY-MM-DD");
        var dtEnd = moment(end, "YYYY-MM-DD");
        //Difference in number of days
        return parseInt(moment.duration(dtEnd.diff(dtStart)).asDays(), 10);
    }

    this.getFormattedNumber = function (number) {
        var result = "";
        var numberWithoutComma = number.replace(/\,/g, "");

        if (numberWithoutComma)
            return $filter('number')(numberWithoutComma, 2);
        return result;
    }

    this.getFormattedNumberAllowNegDecimal15 = function (number) {
        var result = "";
        var numberWithoutComma = number.replace(/\,/g, "");

        if ((numberWithoutComma.split(".").length - 1) > 1)
            return number;

        var idx = numberWithoutComma.indexOf('.');

        if (idx > 0) {
            if (numberWithoutComma.substring(0, idx) > 0 && numberWithoutComma.substring(0, idx).length > 13 )
            {
                numberWithoutComma = numberWithoutComma.slice(0, idx - 2) + numberWithoutComma.slice(idx - 1);
            }
        }
        
        if (idx <= 0) {
            if (numberWithoutComma > 0 && numberWithoutComma.length > 13) {
                numberWithoutComma = numberWithoutComma.substring(0, numberWithoutComma.length - 1);

            }
        }

        if (numberWithoutComma)
            return $filter('number')(numberWithoutComma, 2);
        return result;
    }
});