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

    //.directive('myRepeatDirective', function() {
    //    return function(scope, element, attrs) {
    //        //angular.element(element).css('color','blue');
    //        if (scope.$last){
    //            utilService.showAlert("hi");
    //        }
    //        scope.$watch('thing', function(){
    //
    //        });
    //    };
    //})
    .controller('TabsController', function($scope, $state) {
        $scope.shouldHide = function() {
            if ($state.current.name == "tab.warning") {
                return true;
            } else {
                return false;
            }
        };
    })
    .controller('MainCtrl', function (constants, $scope, $ionicLoading, $rootScope,
                                      feqhiatService, $state, utilService, $localStorage) {

        //var counter = 0;

        $scope.$on('$ionicView.beforeEnter', function() {
            //check if the device has app_id (HERE the device id is generated from the server)
            //utilService.showAlert($localStorage['device_id']);
            var successAddDevice = function () {
                // save the data to local storage and use it
                $localStorage['device_id'] = $scope.device_id;
                $ionicLoading.hide();
            };
            // First time to install the app
            if($localStorage['device_id'] == undefined || $localStorage['device_id'] == '0')
            {
                // create ID from the server and return it
                feqhiatService.addDevice($scope, successAddDevice);
                //utilService.showAlert($localStorage.app_id);
            }
        });
        $scope.$on('$ionicView.enter', function(){
            // Anything you can think of
            //utilService.showAlert("I entered");
            // reset all rootScope variables
            $rootScope.problem = new Object();
            //$rootScope.problem.is_answer = false;
            $rootScope.problem_id = 0;
        });


        $ionicLoading.show({
            template: 'الرجاء الانتظار'
        });

        var successAllData = function () {
            // save the data to local storage and use it
            $localStorage['allData'] = $scope.allData;
            if(!constants.is_admin) { // if not admin, hide control panel
                var itms = new Array();

                for (var i = 0; i < $localStorage['allData'].items.length; i++) {
                    if ($localStorage['allData'].items[i].item_id != 6) // not control panel
                    {
                        itms.push($localStorage['allData'].items[i]);
                    }
                }
                $scope.allItems = itms;
            }
            else
                $scope.allItems =  $localStorage['allData'].items;
            $ionicLoading.hide();
        };

        var successAllParam = function () {
            $ionicLoading.hide();
            // if version is different force to update
            //utilService.showAlert($localStorage['al_params']);
            if(constants.app_version != utilService.getParamByName("app_version", $scope.al_params).value)
            {
                /// show the update page
                console.log("update");
                //$ionicHistory.nextViewOptions({
                //    historyRoot: true,
                //    disableBack: true
                //});
                $state.go('tab.warning');
            }
            // if params not saved before
            else if($localStorage['al_params'] ==  undefined)
            {
                // save it to local storage
                console.log("update DB");
                //console.log(utilService.getParamByName("db_version", $localStorage['al_params']));
                $localStorage['al_params'] = $scope.al_params;
                feqhiatService.getAllData($scope, successAllData);
            }
            else if(utilService.getParamByName("db_version", $localStorage['al_params']).value != utilService.getParamByName("db_version", $scope.al_params).value)
            {
                console.log("update DB 2");
                console.log(utilService.getParamByName("db_version", $localStorage['al_params']));
                $localStorage['al_params'] = $scope.al_params;
                feqhiatService.getAllData($scope, successAllData);
            }
            // check if db version is the same in both server and local
            else //if($window.localStorage['al_params'].db_version == $scope.al_params.db_version)
            {
                //$scope.allData.items;
                if(!constants.is_admin) { // if not admin, hide control panel
                    var itms = new Array();

                    for (var i = 0; i < $localStorage['allData'].items.length; i++) {
                        if ($localStorage['allData'].items[i].item_id != 6) // not control panel
                        {
                            itms.push($localStorage['allData'].items[i]);
                        }
                    }
                    $scope.allItems = itms;
                }
                else
                    $scope.allItems =  $localStorage['allData'].items;
                $ionicLoading.hide();
            }
            // if not the same, get all data
            //else
            //{
            //    feqhiatService.getAllData($scope, successAllData);
            //}

            // else use the local one
        };

        feqhiatService.getAllParam($scope, successAllParam);

        $scope.navigateToView = function (itemID)
        {
            $rootScope.problem = new Object();
            $rootScope.item_id = itemID;
            //utilService.showAlert($rootScope.item_id);
            if(itemID == 1) // Send Question
                $state.go('tab.send');
            else if(itemID == 5) // News
                $state.go('tab.news_list'); // TO DO
            else if(itemID == 6) // Control Panel
            {
                if(constants.is_admin)
                {
                    $rootScope.problem.is_answer = true;
                    $state.go('tab.problem_list');
                }

            }
            else if(itemID == 7) // my questions
            {
                $rootScope.problem_id =0;
                $rootScope.problem = new Object();
                $rootScope.problem.is_mine = true;
                $rootScope.problem.device_id = $localStorage['device_id'];
                $state.go('tab.problem_list');
            }
            else // show books
                $state.go('tab.books');
        };
    })

    .controller('BookCtrl',
        function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope) {
            //$rootScope.itemID = '';
            $scope.$on('$ionicView.enter', function(){
                $rootScope.book_id = '0';
                $rootScope.chapter_id = '0';
                $rootScope.problem_id = '0';
                $scope.allBooks =  $localStorage.allData.books;
            });


            $scope.navigateToView = function (bookID)
            {
                $rootScope.book_id = bookID;
                $state.go('tab.chapters');
            };
        }

    )

    .controller('ChapterCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope) {
        /*$rootScope.itemID = '';
        $rootScope.bookID = '';*/
        $scope.$on('$ionicView.enter', function() {
            $rootScope.chapter_id = '0';
            $rootScope.problem_id = '0';
            $scope.chapters = utilService.getBookChapters($rootScope.book_id, $localStorage.allData.chapters);
        });
        $scope.navigateToView = function (chapterID)
        {
            $rootScope.chapter_id = chapterID;
            $rootScope.problem = new Object();
            $rootScope.problem.item_id = $rootScope.item_id;
            $rootScope.problem.book_id = $rootScope.book_id;
            $rootScope.problem.chapter_id = $rootScope.chapter_id;
            $state.go('tab.problem_list');
        };
    }

)

    .controller('ProblemListCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope, $ionicLoading) {

        $scope.$on('$ionicView.beforeEnter', function() {
            $rootScope.problem_id = 0;
            $scope.problem_list = null;
            $scope.isMore = false;
            $scope.startIndex = 0;
            $scope.count = 20;
            $scope.allCount =0;
            $scope.problem_list = new Array();
        });

        var successProblemList = function () {
            $scope.problem_list =  $scope.problem_list.concat($scope.allData.data);//$scope.allData.items;
            $scope.allCount = $scope.allData.time;
            $ionicLoading.hide();
            if($scope.allCount > $scope.problem_list.length)
                $scope.isMore = true;
            else
                $scope.isMore = false;

            $scope.startIndex += $scope.count;
        };
        $scope.$on('$ionicView.enter', function() {
            $scope.getProblems();
        });

        $scope.getProblems = function () {

            feqhiatService.getProblemList($rootScope, $scope, successProblemList, $rootScope.problem);
        };

        $scope.navigateToView = function (problemID, status)
        {
            $rootScope.problem_id = problemID;
            $rootScope.problem.status = status;
            if($rootScope.problem.is_answer)
                $state.go('tab.answer');
            else if($rootScope.problem.is_mine && (status == '1' || status == '2'))
                $state.go('tab.send');
            else
                $state.go('tab.singleProblem');
        };
    }

)

    .controller('ProblemCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope, $ionicLoading) {
        var successProblemSolutions = function () {
            $scope.solutions =  $scope.allData.data;//$scope.allData.items;
            $scope.problem = $scope.allData.problem[0];
            $ionicLoading.hide();
        };
        $scope.$on('$ionicView.beforeEnter', function() {
            $scope.solutions = new Object();
            //$scope.problem_text = "";
            $scope.problem = null;
        });
        $scope.$on('$ionicView.enter', function() {

            feqhiatService.getProblemSolutions($rootScope, $scope, successProblemSolutions);
        });

        $scope.share = function () {
            //utilService.showAlert("111");
            feqhiatService.share($scope.problem, $scope.solutions, false);
        };

    }

)





    .controller('NewsListCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope, $ionicLoading) {

        $scope.$on('$ionicView.beforeEnter', function() {
            $rootScope.news_id = 0;
            $scope.news_list = null;
            $rootScope.newsContent = "";
        });

        var successNewsList = function () {
            $scope.news_list =  $scope.allData.news;//$scope.allData.items;
            $ionicLoading.hide();
        };
        $scope.$on('$ionicView.enter', function() {
            feqhiatService.getNewsList($rootScope, $scope, successNewsList);
        });


        $scope.navigateToView = function (news)
        {
            $rootScope.news = news;
            $state.go('tab.single_news');
        };
    }

)

    .controller('NewsCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope) {
        $scope.$on('$ionicView.enter', function() {

            $scope.news = $rootScope.news;
        });

        //$scope.share = function () {
        //    //utilService.showAlert("111");
        //    feqhiatService.share($scope.problem, $scope.solutions, false);
        //};

    }

)







    .controller('SendCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope, $ionicLoading) {
        var successProblemSolutions = function () {
            $scope.solutions =  $scope.allData.data;//$scope.allData.items;
            $scope.problem = $scope.allData.problem[0];
            $scope.problem.problem = $scope.problem.problem_text;
            //$scope.is_visible = true;
            $ionicLoading.hide();
        };

        $scope.$on('$ionicView.beforeEnter', function() {
            $scope.solutions = new Object();
            $scope.is_visible = false;
        });

        $scope.$on('$ionicView.enter', function() {
            $scope.faqih_list = $localStorage['allData'].faqih;
            if($rootScope.problem.status == '1')
            {
                //utilService.showAlert($rootScope.problem.status+","+$rootScope.problem_id);
                //$rootScope.problem_id = $rootScope.problem.problem_id;
                $scope.is_visible = true;
                feqhiatService.getProblemSolutions($rootScope, $scope, successProblemSolutions);
            }
        });
        $scope.books = $localStorage['allData'].books;
        $scope.getChapters = function(bookID) {
            //console.log(bookID);
            $scope.chapters = utilService.getBookChapters(bookID, $localStorage['allData'].chapters);
        };

        var successSend = function () {
            $ionicLoading.hide();
            $scope.problem = null;
            utilService.showAlert("تم إرسال الإستفتاء وسيتم الرد عليك في أقرب وقت");
            $state.go('tab.main');
        };

        $scope.sendFatwa = function (problem, new_status) {
            //console.log(problem);
            problem.device_id = $localStorage.device_id;
            problem.new_status = new_status;
            feqhiatService.sendFatwa($scope, successSend, problem);
        };

        //console.log($localStorage['allData']);
    }

)

    .controller('AnswerCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope, $ionicLoading) {
        var successProblemSolutions = function () {

            $scope.solutions =  $scope.allData.data;//$scope.allData.items;
            //alert("hi");
            $scope.problem = $scope.allData.problem[0];
            if($scope.solutions.length > 0)
            {
                //alert($scope.solutions[0].solution_text);
                $scope.problem.solution = $scope.solutions[0].solution_text;
                $scope.problem.solution_id = $scope.solutions[0].solution_id;
            }
            $ionicLoading.hide();
        };

        $scope.$on('$ionicView.beforeEnter', function() {
            $scope.solutions = new Object();
            $scope.problem = "";
        });

        $scope.$on('$ionicView.enter', function() {
            $scope.books = $localStorage['allData'].books;
            $scope.faqih_list = $localStorage['allData'].faqih;
            feqhiatService.getProblemSolutions($rootScope, $scope, successProblemSolutions);
        });

        $scope.getChapters = function(bookID) {
            //console.log(bookID);
            //utilService.showAlert(bookID);
            $scope.chapters = utilService.getBookChapters(bookID, $localStorage['allData'].chapters);
        };
        $scope.$on('$ionicView.afterEnter', function(){
            //$scope.getChapters($scope.problem.book_id);
        });

        var successAnswer = function () {
            $ionicLoading.hide();
            $scope.problem = null;

            utilService.showAlert("تم الارسال بنجاح");
            $state.go('tab.problem_list');
        };

        $scope.saveAnswer = function (problem, status) {
            //console.log(problem);
            //utilService.showAlert(status);
            problem.status = status;
            problem.problem_id = $rootScope.problem_id;
            feqhiatService.saveAnswer($scope, successAnswer, problem);
        };

        $scope.cancel = function () {
            $state.go('tab.problem_list');
        };

        //console.log($localStorage['allData']);
    }

)

  .controller('RecentCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope) {

        //$scope.getProblemList = function (problem) {
            //console.log(problem);
            //feqhiatService.getProblemList($rootScope, $scope, successProblemList, problem);

        $scope.$on('$ionicView.enter', function(){
            $rootScope.problem = new Object();
            var prob = new Object();
            prob.latest = true;
            $rootScope.problem_id = 0;
            $rootScope.problem = prob;
            $state.go("tab.problem_list");
        });

        //console.log($localStorage['allData']);
    }

)

  .controller('SearchCtrl',
    function ($scope, feqhiatService, $state, utilService, $localStorage, $rootScope) {
        $scope.faqih_list = $localStorage['allData'].faqih;
        $scope.books = $localStorage['allData'].books;
        $scope.getChapters = function(bookID) {
            //console.log(bookID);
            $scope.chapters = utilService.getBookChapters(bookID, $localStorage['allData'].chapters);
        };

        $scope.getProblemList = function (problem) {
            //console.log(problem);
            //feqhiatService.getProblemList($rootScope, $scope, successProblemList, problem);
            $rootScope.problem = new Object();
            $rootScope.problem = problem;
            $state.go("tab.problem_list");
        };

        //console.log($localStorage['allData']);
    }

)
    .controller('WarningCtrl',
    function ($scope, constants, $ionicNavBarDelegate) {

        $ionicNavBarDelegate.showBackButton(false);
        //$scope.$on('$ionicView.afterEnter', function(){
        //    $ionicHistory.clearHistory();
        //    $ionicHistory.nextViewOptions({
        //        historyRoot: true
        //    });
        //});

        $scope.goToUpdate = function () {
            var url = "";
            if(ionic.Platform.platform() == "ios")
                url = constants.iosLink;
            else if(ionic.Platform.platform() == "android")
                url = constants.androidLink;
            else
                url = constants.mainLink;
//utilService.showAlert(ionic.Platform.platform());
            window.open(url);
            //cordova.InAppBrowser.open(url, "_system", "location=true");
        };

        //console.log($localStorage['allData']);
    }

)

  .controller('AboutCtrl', function($scope) {
    $scope.settings = {
      enableFriends: true
    };
  });
