angular.module('starter.services', [])

    .factory('feqhiatService', function (constants, $http, $rootScope, utilService, $cordovaSocialSharing,$ionicLoading,$cordovaClipboard, $localStorage) {
        var feqhiatService = {};

        ///////////// ADD DEVICE ID /////////////////
        feqhiatService.addDevice = function (theScope, successFunc) {
            var url = constants.addDevice+"&platform="+ionic.Platform.platform();
            //utilService.showAlert(url);
            $http({
                method: "GET",
                url: url
            }).success(function (data) {
                theScope.device_id = data.device_id;
                //utilService.showAlert(theScope.device_id);
                if (successFunc) {
                    successFunc();
                }

            }).error(function (data, status) {
                if($ionicLoading)
                    $ionicLoading.hide();
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "11");
            });
        };

        //////////  GET PARAMS //////////////
        feqhiatService.getAllParam = function (theScope, successFunc) {
            var url = constants.param_url+"&device_id="+$localStorage['device_id'];
            $http({
                method: "GET",
                url: url
            }).success(function (data) {
                var allData = data.data;
                constants.is_admin = allData.is_admin; //true;// TEMP
                //~utilService.showAlert
                constants.user_name = allData.user_name;
                theScope.al_params = allData.params;
                //utilService.showAlert(constants.user_name);

                if (successFunc) {
                    //console.log(constants.is_admin + ",  " + constants.user_name);
                    successFunc();
                }

            }).error(function (data, status) {
                if($ionicLoading)
                    $ionicLoading.hide();
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "1");
            });
        };

        //////////////////  GET ALL PRIMARY DATA //////////////
        feqhiatService.getAllData = function (theScope, successFunc) {
            var url = constants.all_data;
            $http({
                method: "GET",
                url: url
            }).success(function (data) {
                //var allData = data.data;
                theScope.allData = data.data;
                if (successFunc) {
                    console.log("success 2");
                    successFunc();
                }

            }).error(function (data, status) {
                if($ionicLoading)
                    $ionicLoading.hide();
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "2");
            });
        };

        /////////////  GET PROBLEM LIST //////////////////
        feqhiatService.getProblemList = function (rootScope, theScope, successFunc, problem) {
            //utilService.showAlert(problem.item_id+", "+ problem.book_id +", "+ problem.chapter_id+", "+ problem.faqih_id);
            var url = constants.problem_list;
            if(problem.item_id != undefined)
                url += "&item_id="+problem.item_id;
            if(problem.book_id != undefined)
                url += "&book_id="+problem.book_id;
            if(problem.chapter_id != undefined)
                url += "&chapter_id="+problem.chapter_id;
            if(problem.faqih_id != undefined)
                url += "&faqih_id="+problem.faqih_id;
            if(problem.is_answer != undefined)
                url += "&is_answer="+problem.is_answer;
            if(problem.latest != undefined)
                url += "&latest="+problem.latest;
            if(problem.problem != undefined)
                url += "&problem="+problem.problem;
            if(problem.device_id != undefined)
                url += "&device_id="+problem.device_id;
            if(theScope.startIndex != undefined)
                url += "&start="+theScope.startIndex;
            if(theScope.count != undefined)
                url += "&count="+theScope.count
            //utilService.showAlert(url);
            $ionicLoading.show({
                template: 'الرجاء الانتظار'
            });

            $http({
                method: "GET",
                url: url
            }).success(function (data) {
                theScope.allData = data.status;
                if (successFunc) {
                    console.log("success 3");
                    $ionicLoading.hide();
                    successFunc();
                }

            }).error(function (data, status) {
                if($ionicLoading)
                    $ionicLoading.hide();
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "3");
            });
        };

        ////////////// GET PROBLEM SOLUTIONS ////////////////
        feqhiatService.getProblemSolutions = function (rootScope, theScope, successFunc) {
            var url = constants.problem_solutions+"&problem_id="+rootScope.problem_id;
            $http({
                method: "GET",
                url: url
            }).success(function (data) {
                theScope.allData = data.status;
                if (successFunc) {
                    console.log("success 4");
                    successFunc();
                }

            }).error(function (data, status) {
                if($ionicLoading)
                    $ionicLoading.hide();
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "4");
            });
        };

        ////////// SEND QUESTION /////////////
        feqhiatService.sendFatwa = function (scopeObj, successFunc, problem) {

            if (problem.problem.trim().length < 10) {
                utilService.showAlert("يجب كتابة السؤال قبل الإرسال");
                return;
            }
            if (problem.faqih_id == -1) {
                problem.faqih_id = 1;
            }
            if (problem.book_id == -1) {
                problem.book_id = 0;
            }
            if (problem.chapter_id == -1) {
                problem.chapter_id = 0;
            }
            $ionicLoading.show({
                template: 'الرجاء الانتظار'
            });

            var send_problem_url = constants.send_problem;
            /*console.log()
            var dataTosend={name:problem.name, mobile:problem.mobile, email:problem.email, problem:problem.problem,
                            faqih_id:problem.faqih_id};*/
            Object.toParams = function ObjectToParams(obj) {
                var p = [];
                for (var key in obj) {
                    p.push(key + '=' + encodeURIComponent(obj[key]));
                }
                return p.join('&');
            };
            $http({
                method: 'POST',
                url:send_problem_url,
                data:Object.toParams(problem),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function successCallback(data) {
                if(successFunc)
                {
                    successFunc();
                }
            }, function errorCallback(response) {
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "5");
            });


        };

        /////////////// ANSWER QUESTION ////////////////
        feqhiatService.saveAnswer = function (scopeObj, successFunc, problem) {

            //utilService.showAlert("444");
            //utilService.showAlert(problem.chapter_id);
            if (problem.solution.trim().length < 3 && problem.status != "0") {
                utilService.showAlert("يرجى كتابة الجواب قبل الحفظ");
                return;
            }
            if (problem.status == undefined) {
                utilService.showAlert("الرجاء الضغط على الزر المطلوب");
                return;
            }
            if (problem.faqih_id == -1) {
                utilService.showAlert("الرجاء اختيار الفقيه");
                return;
            }
            if (problem.book_id == -1) {
                utilService.showAlert("الرجاء اختيار الكتاب");
                return;
            }
            if (problem.chapter_id == -1) {
                utilService.showAlert("الرجاء اختيار الباب");
                return;
            }
            $ionicLoading.show({
                template: 'الرجاء الانتظار'
            });

            var save_answer_url = constants.saveSolution;
            //utilService.showAlert("555");
            Object.toParams = function ObjectToParams(obj) {
                var p = [];
                for (var key in obj) {
                    p.push(key + '=' + encodeURIComponent(obj[key]));
                }
                return p.join('&');
            };
            $http({
                method: 'POST',
                url:save_answer_url,
                data:Object.toParams(problem),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function successCallback(data) {
                if(successFunc)
                {
                    successFunc();
                }
            }, function errorCallback(response) {
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "6");
            });


        };

        /////////////  GET NEWS LIST //////////////////
        feqhiatService.getNewsList = function (rootScope, theScope, successFunc, problem) {
            //utilService.showAlert(problem.item_id+", "+ problem.book_id +", "+ problem.chapter_id+", "+ problem.faqih_id);
            var url = constants.newsList;
            //utilService.showAlert(url);
            $ionicLoading.show({
                template: 'الرجاء الانتظار'
            });

            $http({
                method: "GET",
                url: url
            }).success(function (data) {
                theScope.allData = data.data;
                if (successFunc) {
                    console.log("success 3");
                    $ionicLoading.hide();
                    successFunc();
                }

            }).error(function (data, status) {
                if($ionicLoading)
                    $ionicLoading.hide();
                utilService.showAlert("حدث خطأ ، الرجاء التأكد من الشبكة"  + "12");
            });
        };

        //////////////// SHARE //////////////////////

        feqhiatService.share = function (problem, solutions, isCopy) {
            var lines = "\n----------------\n";
            var seprate = "\n==========================\n";
            var shareText = "تطبيق فقهيات المحدثين" + seprate +"\n";
            shareText += "السؤال: " + lines+"\n";
            shareText += problem.problem_text + seprate+"\n";
            shareText += "الجواب: " + lines+"\n";
            for (var i = 0; i < solutions.length; i++) {
                shareText = shareText + solutions[i].faqih_name + "\n" + solutions[i].solution_text + lines+"\n";
            }
            shareText += seprate;

            shareText += "عن طريق برنامج فقهيات المحدثين ، بإشراف سماحة الشيخ علي الثنيان" + "\n" + "لا يجوز التصرف في محتوى  الرسالة" +seprate+"\n";
            shareText += "" + seprate+"\n";
            shareText += "لتحميل التطبيق: "+"\n"+"\n";
            shareText += "الأندرويد: " + constants.androidLink +"\n"+"\n";
            shareText += "الآيفون والآيباد: " + constants.iosLink;

            //if (social == 'wa') {
            //    $cordovaSocialSharing
            //        .shareViaWhatsApp(shareText)
            //        .then(function (result) {
            //            // Success!
            //        }, function (err) {
            //            // An error occurred. Show a message to the user
            //        });
            //}
            //else if (social == 'fb') {
            //    $cordovaSocialSharing
            //        .shareViaFacebook(shareText)
            //        .then(function (result) {
            //            // Success!
            //        }, function (err) {
            //            // An error occurred. Show a message to the user
            //        });
            //
            //}
            //else
            if (!isCopy) {
                //utilService.showAlert($cordovaSocialSharing);
                $cordovaSocialSharing
                    .share(shareText)
                    .then(function (result) {
                        // Success!
                    }, function (err) {
                        // An error occurred. Show a message to the user
                    });

            }
            else {
                $cordovaClipboard
                    .copy(shareText)
                    .then(function () {
                        // success
                    }, function () {
                        // error
                    });

            }

        };


        return feqhiatService;
    });
