(function (angular) {
    "use strict";
    angular
        .module('folderPluginWidget')
        .controller('folderPluginCtrl', ['$scope', '$sce', '$timeout', '$rootScope', 'Messaging', 'Utility',
            function ($scope, $sce, $timeout, $rootScope, Messaging, Utility) {
                $scope.exLvl = [
                                   { active: "Little/No Exercise", level: 1.2 },
                                   { active: "Light exercise (1-3 days per week)", level: 1.375 },
                                   { active: "Moderate exercise (3-5 days per week)", level: 1.55 },
                                   { active: "Heavy exercise (6-7 days per week)", level: 1.725 },
                                   { active: "Very heavy exercise", level: 1.9 }
                ];
                $scope.meals = 3;
                $scope.gendershow = 1;
                $scope.calculate = function () {
                    $scope.malebmr = Math.round(66 + (6.2 * $scope.pounds) + (12.7 * (12 * $scope.feet + $scope.inches)) - (6.76 * $scope.years));
                    $scope.femalebmr = Math.round(655.1 + (4.35 * $scope.pounds) + (4.7 * (12 * $scope.feet + $scope.inches)) - (4.7 * $scope.years));
                }
                $scope.calculatetdee = function () {
                    $scope.maletdee = Math.round($scope.selectEx.level * $scope.malebmr);
                    $scope.femaletdee = Math.round($scope.selectEx.level * $scope.femalebmr);
                }
                $scope.lowlossCalc = function () {
                    $scope.lossShow = 1;
                    $scope.lowloss = Math.round($scope.maletdee * .85);
                    $scope.felowloss = Math.round($scope.femaletdee * .85);
                    $scope.calculatemealplan();
                }
                $scope.medlossCalc = function () {
                    $scope.lossShow = 2;
                    $scope.medloss = Math.round($scope.maletdee * .80);
                    $scope.femedloss = Math.round($scope.femaletdee * .80);
                    $scope.calculatemealplan();
                }
                $scope.highlossCalc = function () {
                    $scope.lossShow = 3;
                    $scope.highloss = Math.round($scope.maletdee * .75);
                    $scope.fehighloss = Math.round($scope.femaletdee * .75);
                    $scope.calculatemealplan();
                }
                $scope.lowgainCalc = function () {
                    $scope.gainShow = 1;
                    $scope.lowgain = Math.round($scope.maletdee * 1.05);
                    $scope.felowgain = Math.round($scope.femaletdee * 1.05);
                    $scope.calculatemealplan();
                }
                $scope.medgainCalc = function () {
                    $scope.gainShow = 2;
                    $scope.medgain = Math.round($scope.maletdee * 1.10);
                    $scope.femedgain = Math.round($scope.femaletdee * 1.10);
                    $scope.calculatemealplan();
                }
                $scope.highgainCalc = function () {
                    $scope.gainShow = 3;
                    $scope.highgain = Math.round($scope.maletdee * 1.15);
                    $scope.fehighgain = Math.round($scope.femaletdee * 1.15);
                    $scope.calculatemealplan();
                }
                $scope.calculatemealplan = function () {
                    if ($scope.gendershow === 1) {
                        document.getElementById("malebtn").style.backgroundColor = "#c91919";
                        document.getElementById("femalebtn").style.background = "none";
                        if ($scope.goal === 1) {
                            document.getElementById("maleloss").style.backgroundColor = "#c91919";
                            document.getElementById("malegain").style.background = "none";
                            document.getElementById("malemain").style.background = "none";
                            if ($scope.lossShow === 1) {
                                document.getElementById("litlossclac").style.backgroundColor = "#c91919";
                                document.getElementById("medlossclac").style.background = "none";
                                document.getElementById("biglossclac").style.background = "none";
                                $scope.mealPlan = "Male Low Intensity Weight Loss";
                                $scope.dailyCal = $scope.lowloss;
                            }
                            if ($scope.lossShow === 2) {
                                document.getElementById("medlossclac").style.backgroundColor = "#c91919";
                                document.getElementById("litlossclac").style.background = "none";
                                document.getElementById("biglossclac").style.background = "none";
                                $scope.mealPlan = "Male Moderate Intensity Weight Loss";
                                $scope.dailyCal = $scope.medloss;
                            }
                            if ($scope.lossShow === 3) {
                                document.getElementById("biglossclac").style.backgroundColor = "#c91919";
                                document.getElementById("medlossclac").style.background = "none";
                                document.getElementById("litlossclac").style.background = "none";
                                $scope.mealPlan = "Male High Intensity Weight Loss";
                                $scope.dailyCal = $scope.highloss;
                            }
                        }
                        if ($scope.goal === 3) {
                            document.getElementById("malegain").style.backgroundColor = "#c91919";
                            document.getElementById("maleloss").style.background = "none";
                            document.getElementById("malemain").style.background = "none";
                            if ($scope.gainShow === 1) {

                                document.getElementById("litgainclac").style.backgroundColor = "#c91919";
                                document.getElementById("medgainclac").style.background = "none";
                                document.getElementById("biggainclac").style.background = "none";
                                $scope.mealPlan = "Male Low Intensity Weight Gain";
                                $scope.dailyCal = $scope.lowgain;
                            }
                            if ($scope.gainShow === 2) {

                                document.getElementById("medgainclac").style.backgroundColor = "#c91919";
                                document.getElementById("litgainclac").style.background = "none";
                                document.getElementById("biggainclac").style.background = "none";
                                $scope.mealPlan = "Male Moderate Intensity Weight Gain";
                                $scope.dailyCal = $scope.medgain;
                            }
                            if ($scope.gainShow === 3) {
                                document.getElementById("biggainclac").style.backgroundColor = "#c91919";
                                document.getElementById("medgainclac").style.background = "none";
                                document.getElementById("litgainclac").style.background = "none";
                                $scope.mealPlan = "Male High Intensity Weight Gain";
                                $scope.dailyCal = $scope.highgain;
                            }
                        }
                        if ($scope.goal === 2) {
                            document.getElementById("malemain").style.backgroundColor = "#c91919";
                            document.getElementById("maleloss").style.background = "none";
                            document.getElementById("malegain").style.background = "none";
                            $scope.mealPlan = "Male Weight Maintain";
                            $scope.dailyCal = $scope.maletdee;
                        }
                    }
                    if ($scope.gendershow === 2) {
                        document.getElementById("femalebtn").style.backgroundColor = "#c91919";
                        document.getElementById("malebtn").style.background = "none";
                        if ($scope.goal === 1) {
                            document.getElementById("femaleloss").style.backgroundColor = "#c91919";
                            document.getElementById("femalegain").style.background = "none";
                            document.getElementById("femalemain").style.background = "none";
                            if ($scope.lossShow === 1) {
                                document.getElementById("felitlossclac").style.backgroundColor = "#c91919";
                                document.getElementById("femedlossclac").style.background = "none";
                                document.getElementById("febiglossclac").style.background = "none";
                                $scope.mealPlan = "Female Low Intensity Weight Loss";
                                $scope.dailyCal = $scope.felowloss;
                            }
                            if ($scope.lossShow === 2) {
                                document.getElementById("femedlossclac").style.backgroundColor = "#c91919";
                                document.getElementById("felitlossclac").style.background = "none";
                                document.getElementById("febiglossclac").style.background = "none";
                                $scope.mealPlan = "Female Moderate Intensity Weight Loss";
                                $scope.dailyCal = $scope.femedloss;
                            }
                            if ($scope.lossShow === 3) {
                                document.getElementById("febiglossclac").style.backgroundColor = "#c91919";
                                document.getElementById("femedlossclac").style.background = "none";
                                document.getElementById("felitlossclac").style.background = "none";
                                $scope.mealPlan = "Female High Intensity Weight Loss";
                                $scope.dailyCal = $scope.fehighloss;
                            }
                        }
                        if ($scope.goal === 3) {
                            document.getElementById("femalegain").style.backgroundColor = "#c91919";
                            document.getElementById("femaleloss").style.background = "none";
                            document.getElementById("femalemain").style.background = "none";
                            if ($scope.gainShow === 1) {
                                document.getElementById("felitgainclac").style.backgroundColor = "#c91919";
                                document.getElementById("femedgainclac").style.background = "none";
                                document.getElementById("febiggainclac").style.background = "none";
                                $scope.mealPlan = "Female Low Intensity Weight Gain";
                                $scope.dailyCal = $scope.felowgain;
                            }
                            if ($scope.gainShow === 2) {
                                document.getElementById("femedgainclac").style.backgroundColor = "#c91919";
                                document.getElementById("febiggainclac").style.background = "none";
                                document.getElementById("felitgainclac").style.background = "none";
                                $scope.mealPlan = "Female Moderate Intensity Weight Gain";
                                $scope.dailyCal = $scope.femedgain;
                            }
                            if ($scope.gainShow === 3) {
                                document.getElementById("febiggainclac").style.backgroundColor = "#c91919";
                                document.getElementById("femedgainclac").style.background = "none";
                                document.getElementById("felitgainclac").style.background = "none";
                                $scope.mealPlan = "Female High Intensity Weight Gain";
                                $scope.dailyCal = $scope.fehighgain;
                            }
                        }
                        if ($scope.goal === 2) {
                            document.getElementById("femalemain").style.backgroundColor = "#c91919";
                            document.getElementById("femaleloss").style.background = "none";
                            document.getElementById("femalegain").style.background = "none";
                            $scope.mealPlan = "Female Weight Maintain";
                            $scope.dailyCal = $scope.femaletdee;
                        }
                    }
                }
                $scope.finalCalc = function () {
                    $scope.protiens = Math.round($scope.pounds * $scope.protienmod);
                    $scope.fats = Math.round($scope.pounds * $scope.fatmod);
                    $scope.fatcal = $scope.fats * 9;
                    $scope.protiencal = $scope.protiens * 4;
                    $scope.carbs = Math.round(($scope.dailyCal - $scope.fatcal - $scope.protiencal) / 4);
                    $scope.mfats = Math.round($scope.fats / $scope.meals);
                    $scope.mprotiens = Math.round($scope.protiens / $scope.meals);
                    $scope.mcarbs = Math.round($scope.carbs / $scope.meals);
                    $scope.mdailyCal = Math.round($scope.dailyCal / $scope.meals);
                    if ($scope.protienmod === .7) {
                        document.getElementById("lowprotienmod").style.backgroundColor = "#c91919";
                        document.getElementById("medprotienmod").style.background = "none";
                        document.getElementById("higprotienmod").style.background = "none";
                    }
                    if ($scope.protienmod === .8) {
                        document.getElementById("medprotienmod").style.backgroundColor = "#c91919";
                        document.getElementById("lowprotienmod").style.background = "none";
                        document.getElementById("higprotienmod").style.background = "none";
                    } if ($scope.protienmod === .9) {
                        document.getElementById("higprotienmod").style.backgroundColor = "#c91919";
                        document.getElementById("medprotienmod").style.background = "none";
                        document.getElementById("lowprotienmod").style.background = "none";
                    } if ($scope.protienmod < .7 || $scope.protienmod > .9) {
                        document.getElementById("inputprotienmod").style.backgroundColor = "#c91919";
                        document.getElementById("medprotienmod").style.background = "none";
                        document.getElementById("higprotienmod").style.background = "none";
                        document.getElementById("lowprotienmod").style.background = "none";
                    }
                    if ($scope.fatmod === .30) {
                        document.getElementById("lowfatmod").style.backgroundColor = "#c91919";
                        document.getElementById("medfatmod").style.background = "none";
                        document.getElementById("higfatmod").style.background = "none";
                    }
                    if ($scope.fatmod === .35) {
                        document.getElementById("medfatmod").style.backgroundColor = "#c91919";
                        document.getElementById("lowfatmod").style.background = "none";
                        document.getElementById("higfatmod").style.background = "none";
                    } if ($scope.fatmod === .40) {
                        document.getElementById("higfatmod").style.backgroundColor = "#c91919";
                        document.getElementById("medfatmod").style.background = "none";
                        document.getElementById("lowfatmod").style.background = "none";
                    } if ($scope.fatmod < .3 || $scope.fatmod > .4) {
                        document.getElementById("inputfatmod").style.backgroundColor = "#c91919";
                        document.getElementById("medfatmod").style.background = "none";
                        document.getElementById("higfatmod").style.background = "none";
                        document.getElementById("lowfatmod").style.background = "none";
                    }
                }
                var view = null;
                var pagesCount = 0;
                var currentPage = 0;
                var loadingData = true;
                $scope.layout12Height = '300px';
                $scope.layout12TotalItem = 0;
                $scope.setWidth = function () {
                    $rootScope.deviceWidth = window.innerWidth || 320;
                };

                function initDeviceSize(callback) {
                    $scope.deviceHeight = window.innerHeight;
                    $scope.deviceWidth = window.innerWidth || 320;
                    $scope.sliderHeight = Math.ceil(9 * $scope.deviceWidth / 16);
                    if (callback) {
                        if ($scope.deviceWidth == 0 || $scope.deviceHeight == 0) {
                            setTimeout(function () {
                                initDeviceSize(callback);
                            }, 500);
                        } else {
                            callback();
                            if (!$scope.$$phase && !$scope.$root.$$phase) {
                                $scope.$apply();
                            }
                        }
                    }
                }

                function preparePluginsData(plugins) {
                    if ($scope.data.design.selectedLayout == 5 || $scope.data.design.selectedLayout == 6) {
                        var temp = [];
                        var currentItem = 0;
                        var pluginsLength = plugins.length;

                        for (var i = 0; i < pluginsLength; i++) {
                            if (i % 2 == 0) {
                                temp[currentItem] = [];
                                temp[currentItem].push(plugins[i]);
                            } else {
                                temp[currentItem].push(plugins[i]);
                                currentItem++;
                            }
                        }

                        $scope.data.plugins = temp;
                    } else if ($scope.data.design.selectedLayout == 12) {
                        var matrix = [], i, k;
                        var matrix = []
                        for (i = 0, k = -1; i < plugins.length; i++) {
                            if (i % 8 === 0) {
                                k++;
                                matrix[k] = [];
                            }
                            matrix[k].push(plugins[i]);
                        }
                        $scope.data.plugins = matrix;
                    } else {
                        $scope.data.plugins = plugins;
                        console.log($scope.data.plugins);
                    }
                }

                /*
                 * bind data to the scope
                 * */
                function bind(data) {
                    $scope.data.design = data.design;

                    if (!$scope.data.design) {
                        $scope.data.design = {
                            backgroundImage: null,
                            selectedLayout: 1,
                            backgroundblur: 0
                        };
                    }
                    if (data.plugins) {
                        var currentCount = Number(data.plugins.length);
                        console.log(data.plugins.length);
                        $scope.loadedPlugins = data.plugins;
                    }
                    

                    preparePluginsData(data.plugins);


                    if (currentCount) {
                        $scope.layout12TotalItem = currentCount;
                    }

                    $scope.data.content = data.content;
                    if ($scope.data.content && $scope.data.content.carouselImages) {
                        initDeviceSize(function () {
                            $timeout(function () {
                                if (!view) {
                                    view = new buildfire.components.carousel.view("#carousel", $scope.data.content.carouselImages);
                                } else {
                                    view.loadItems($scope.data.content.carouselImages);
                                }
                            }, 1000);
                        });
                    }

                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                }

                $scope.safeHtml = function (html) {
                    if (html) {
                        var $html = $('<div />', { html: html });
                        $html.find('iframe').each(function (index, element) {
                            var src = element.src;
                            console.log('element is: ', src, src.indexOf('http'));
                            src = src && src.indexOf('file://') != -1 ? src.replace('file://', 'http://') : src;
                            element.src = src && src.indexOf('http') != -1 ? src : 'http:' + src;
                        });
                        return $sce.trustAsHtml($html.html());
                    }
                };

                var searchOptions = { pageIndex: 0, pageSize: 10 };

                function dataLoadedHandler(result) {
                    $scope.data = result.data;
                    $scope.deepLinkList = result.data._buildfire.plugins.result;

                    $scope.$digest();
                    searchOptions.pageIndex = 0;
                    var pluginsList = null;
                    if (result && result.data && !angular.equals({}, result.data) && result.data.content && result.data.design) {
                        if (result.data.content && result.data.content.loadAllPlugins) {
                            buildfire.components.pluginInstance.getAllPlugins(searchOptions, function (err, res) {
                                $scope.imagesUpdated = false;
                                pagesCount = Math.ceil(res.total / searchOptions.pageSize);
                                result.data.plugins = res.data;

                                bind(result.data);
                                loadingData = false;
                                if (pagesCount > 1)
                                    $scope.paging();
                                $scope.imagesUpdated = !!result.data.plugins;
                            });
                        } else {
                            $scope.imagesUpdated = false;
                            pluginsList = result.data._buildfire.plugins;

                            if (result.data._buildfire && pluginsList && pluginsList.result && pluginsList.data) {
                                result.data.plugins = Utility.getPluginDetails(result.data._buildfire.plugins.result, result.data._buildfire.plugins.data);
                            }
                            bind(result.data);
                            $scope.imagesUpdated = !!result.data.plugins;
                        }
                    }
                };

                /*
                 * Go pull saved data
                 * */
                function loadData() {

                    buildfire.datastore.getWithDynamicData(function (err, result) {
                        if (err) {
                            console.error("Error: ", err);
                            return;
                        }
                        if (result.id) {
                            dataLoadedHandler(result);
                        } else {
                            var obj = {
                                data: Utility.getDefaultScopeData()
                            }
                            dataLoadedHandler(obj);
                        }
                    });
                }

                loadData();

                /**
                 * when a refresh is triggered get reload data
                 */
                function resetPaging() {
                    pagesCount = 0;
                    searchOptions.pageIndex = currentPage = 0;
                    loadingData = true;
                    $scope.data.plugins = [];
                }

                function onDatastoreChange(hardRefresh) {
                    resetPaging();
                    loadData();
                }

                buildfire.datastore.onRefresh(onDatastoreChange);

                buildfire.datastore.onUpdate(function (result) {
                    resetPaging();
                    dataLoadedHandler(result);
                });


                $scope.navigateToPlugin = function (plugin) {

                    buildfire.navigation.navigateTo({
                        pluginId: plugin.pluginTypeId,
                        instanceId: plugin.instanceId,
                        title: plugin.title,
                        folderName: plugin.folderName
                    });
                };
                $scope.navigateSignIn = function (plugin) {

                    buildfire.navigation.navigateTo({
                        pluginId: plugin.token,
                        instanceId: plugin.instanceId,
                        title: plugin.title,
                        folderName: plugin.pluginTypeId
                    });
                };



                Messaging.onReceivedMessage = function (event) {
                    if (event) {
                        var plugin = event.message.data;
                        switch (event.name) {
                            case 'OPEN_PLUGIN':
                                console.log('came here plugin', event.message.data);
                                var fName = '';
                        if (plugin && plugin.pluginType && plugin.pluginType.folderName)
                            fName = plugin.pluginType.folderName;
                        else if (plugin && plugin.folderName)
                            fName = plugin.folderName;

                        buildfire.navigation.navigateTo({
                            pluginId: plugin.pluginId,
                            instanceId: plugin.instanceId,
                            title: plugin.title,
                            folderName: fName
                        });
                                break;
                        }
                    }
                };
            }]);
})(window.angular);