(function (angular) {
    "use strict";
    var filedata;

    function handleFileSelect(evt) {
        var file = evt.target.files[0];

        Papa.parse(file, {
            header: true,
            dynamicTyping: true,
            complete: function (results) {
                filedata = results;
                console.log(filedata);
            }
        });
    }

    $(document).ready(function () {
        $("#csv-file").change(handleFileSelect);
    });
    angular
        .module('folderPluginContent')
        .controller('folderPluginCtrl', ['$scope', 'Messaging', 'Utility',
            function ($scope, Messaging, Utility) {
                var pageSize = 999999;

                $scope.groups = [
        {
            "main": "All Meal",
            "second": undefined
        }, {
            "main": "Breakfast",
            "second": "Breakfast"
        }, {
            "main": "Lunch",
            "second": "Lunch"
        }, {
            "main": "Gourmet Dinner",
            "second": "Gourmet Dinner"
        }, {
            "main": "Snacks",
            "second": "Snacks"
        }];
                $scope.options = [
                    {
                        "calOption": "100 Calories",
                        "value": "true",
                    },
                {
                    "calOption": "300 Calories",
                    "value": "true",
                },
                {
                    "calOption": "600 Calories",
                    "value": "true",
                },
                {
                    "calOption": "900 Calories",
                    "value": "true",
                }
                ];
                $scope.calswap = function () {
                    if ($scope.calSearch === "100 Calories") {
                        if ($scope.exLib.data.onecalShow === true) {
                            $scope.oneFilter = true;
                            $scope.threeFilter = true;
                            $scope.sixFilter = true;
                            $scope.nineFilter = true;
                        }
                    }
                    if ($scope.calSearch === "300 Calories") {
                        if ($scope.exLib.data.threecalShow === true) {
                            $scope.oneFilter = true;
                            $scope.threeFilter = true;
                            $scope.sixFilter = true;
                            $scope.nineFilter = true;
                        }
                    }
                    if ($scope.calSearch === "600 Calories") {
                        if ($scope.exLib.data.sixcalShow === true) {
                            $scope.oneFilter = true;
                            $scope.sixFilter = true;
                            $scope.threeFilter = true;
                            $scope.nineFilter = true;
                        }
                    }
                    if ($scope.calSearch === "900 Calories") {
                        if ($scope.exLib.data.ninecalShow === true) {
                            $scope.oneFilter = false;
                            $scope.threeFilter = false;
                            $scope.sixFilter = false;
                            $scope.nineFilter = true;
                        }
                    }
                }
                $scope.edit = function (x) {
                    $scope.displayEx = true;
                    $scope.exCardFilter = x.data.title;
                    console.log($scope.exCardFilter);
                    console.log($scope.displayEx);
                }
                $scope.hide = function () {
                    $scope.displayEx = false;
                    console.log($scope.displayEx);
                }

                $scope.search = function () {
                    $scope.status = 'searching names...';
                    buildfire.datastore.search({
                        filter: {}
                        , page: 0
                        , pageSize: pageSize + 1 // the plus one is to check if there are any more
                        , sort: {}
                    }, 'exerciseLib', function (err, results) {
                        if (err)
                            $scope.status = 'error!';
                        else {
                            $scope.status = 'loading...';
                            $scope.hasMore = results.length > pageSize;
                            if ($scope.hasMore) results.splice(results.length - 1);
                            $scope.exLib = results;
                            $scope.status = '';
                            $scope.$apply();
                            console.log(JSON.stringify($scope.exLib));
                        }
                    });
                };
                $scope.oneshow = function () {
                    $scope.onecalShow = $scope.one;
                }

                $scope.search('/*');
                $scope.insert = function () {
                    buildfire.datastore.insert({
                        title:$scope.title,
                        pic: $scope.pic,
                        type: $scope.type,
                        onecalShow: $scope.onecalShow,
                        onecal1:    $scope.onecal1,
                        onecal2:    $scope.onecal2,
                        onecal3:    $scope.onecal3,
                        onecal4:    $scope.onecal4,
                        onecal5:    $scope.onecal5,
                        onecal6:    $scope.onecal6,
                        onecal7:    $scope.onecal7,
                        onecal8: $scope.onecal8,
                        onecal9: $scope.onecal9,
                        threecalShow: $scope.threecalShow,
                        threecal1:    $scope.threecal1,
                        threecal2:    $scope.threecal2,
                        threecal3:    $scope.threecal3,
                        threecal4:    $scope.threecal4,
                        threecal5:    $scope.threecal5,
                        threecal6:    $scope.threecal6,
                        threecal7:    $scope.threecal7,
                        threecal8:    $scope.threecal8,
                        threecal9:    $scope.threecal9,
                        sixcalShow: $scope.sixcalShow,
                        sixcal1:    $scope.sixcal1,
                        sixcal2:    $scope.sixcal2,
                        sixcal3:    $scope.sixcal3,
                        sixcal4:    $scope.sixcal4,
                        sixcal5:    $scope.sixcal5,
                        sixcal6:    $scope.sixcal6,
                        sixcal7:    $scope.sixcal7,
                        sixcal8:    $scope.sixcal8,
                        sixcal9:    $scope.sixcal9,
                        ninecalShow: $scope.ninecalShow,
                        ninecal1:    $scope.ninecal1,
                        ninecal2:    $scope.ninecal2,
                        ninecal3:    $scope.ninecal3,
                        ninec4al:    $scope.ninecal4,
                        ninecal5:    $scope.ninecal5,
                        ninecal6:    $scope.ninecal6,
                        ninecal7:    $scope.ninecal7,
                        ninecal8:    $scope.ninecal8,
                        ninecal9:    $scope.ninecal9,
                        step1: $scope.step1,
                        step2: $scope.step2,
                        step3: $scope.step3,
                        step4: $scope.step4,
                        step5: $scope.step5,
                        step6: $scope.step6,
                        step7: $scope.step7,
                        step8: $scope.step8,
                        step9: $scope.step9
                    }, 'exerciseLib', false, function () {
                        $scope.$apply();
                        $scope.search('/*');
                    });
                };
                $scope.bulkadd = function () {
                    buildfire.datastore.bulkInsert(filedata.data, 'exerciseLib', function (err, data) {
                        console.log(JSON.stringify(data));
                        });
                    }
                    
                $scope.delete = function (n) {
                    buildfire.datastore.delete(n.id, 'exerciseLib', function (err, status) {
                        if (err)
                            alert('there was a problem deleteing your data');
                        else
                            $scope.search('/*');
                    });
                };
                $scope.updateName = function (n) {
                    /// wait until there is half a second of no more changes then update the server
                    setTimeout(function () {

                        buildfire.datastore.update(n.id, n.data, 'exerciseLib', function (e) {
                            if (e) alert(JSON.stringify(e));
                        });
                    }, 500);
                };
                var tmpCarousalData = null;
                var editor = new buildfire.components.carousel.editor("#carousel");
                var _buildfire = {
                    plugins: {
                        dataType: "pluginInstance",
                        data: []
                    }
                };
                var _design = {
                    backgroundImage: null,
                    selectedLayout: 1,
                    backgroundblur: 0,
                    hideText: false
                };
                var navigationCallback = function (pluginData) {
                    Messaging.sendMessageToWidget({
                        name: 'OPEN_PLUGIN',
                        message: {
                            data: pluginData
                        }
                    });
                };
                var plugins = new buildfire.components.pluginInstance.sortableList("#plugins", [], { showIcon: true, confirmDeleteItem: false }, undefined, undefined, { itemEditable: true, navigationCallback: navigationCallback });
                var tmrDelay = null;
                var updateItem = null;
                $scope.editorOptions = Utility.getEditorOptions();
                $scope.masterData = Utility.getDefaultScopeData();
                $scope.datastoreInitialized = false;

                function isUnchanged(data) {
                    return angular.equals(data, $scope.masterData);
                }

                function updateMasterItem(data) {
                    $scope.masterData = angular.copy(data);
                }

                //Go pull any previously saved data
                buildfire.datastore.getWithDynamicData(function (err, result) {
                    if (!err) {
                        $scope.datastoreInitialized = true;
                    } else {
                        console.error("Error: ", err);
                        return;
                    }

                    if (!result.id) {
                        result.data = Utility.getDefaultScopeData();
                    }

                    if (result && result.data && !angular.equals({}, result.data)) {
                        updateMasterItem(result.data);
                        $scope.data = result.data;
                        $scope.id = result.id;
                        if ($scope.data && $scope.data.content && $scope.data.content.carouselImages) {
                            editor.loadItems($scope.data.content.carouselImages);
                        }
                        if ($scope.data && $scope.data._buildfire && $scope.data._buildfire.plugins && $scope.data._buildfire.plugins.result) {
                            var pluginsData = Utility.getPluginDetails($scope.data._buildfire.plugins.result, $scope.data._buildfire.plugins.data);
                            if ($scope.data.content && $scope.data.content.loadAllPlugins) {
                                if (pluginsData.length) {
                                    plugins.loadItems(pluginsData, "loadAll");
                                    $("#plugins").find(".carousel-items").hide();
                                } else {
                                    plugins.loadAllItems();
                                    $("#plugins").find(".carousel-items").hide();
                                }
                            } else {
                                plugins.loadItems(pluginsData, "selected");
                                $("#plugins").find(".carousel-items").show();
                            }
                        }

                        if ($scope.data && !$scope.data._buildfire) {
                            updateItem = angular.copy($scope.data);
                            updateItem._buildfire = _buildfire;
                            updateMasterItem(updateItem);
                            $scope.data = angular.copy(updateItem);
                        }

                        if ($scope.data && !$scope.data.design) {
                            updateItem = angular.copy($scope.data);
                            updateItem.design = _design;
                            updateMasterItem(updateItem);
                            $scope.data = angular.copy(updateItem);
                        }
                        if (tmrDelay) clearTimeout(tmrDelay);
                    }


                    /*
                     * watch for changes in data and trigger the saveDataWithDelay function on change
                     * */
                    $scope.$watch('data', saveDataWithDelay, true);
                    Utility.digest($scope);
                });

                /*
                 * Call the datastore to save the data object
                 */
                var saveData = function (newObj) {
                    if (!$scope.datastoreInitialized) {
                        console.error("Error with datastore didn't get called");
                        return;
                    }

                    if (newObj == undefined) return;
                    if ($scope.frmMain.$invalid) {
                        console.warn('invalid data, details will not be saved');
                        return;
                    }

                    if (newObj._buildfire && newObj._buildfire.plugins) {
                        newObj._buildfire.plugins.result = plugins.items;
                    }

                    updateMasterItem(newObj);

                    Utility.save(newObj);
                };

                /*
                 * create an artificial delay so api isnt called on every character entered
                 * */
                var saveDataWithDelay = function (newObj) {

                    if (tmrDelay) clearTimeout(tmrDelay);
                    if (isUnchanged(newObj)) {
                        return;
                    }
                    if (newObj.default) {
                        newObj = Utility.getDefaultScopeBlankData();
                        if (tmpCarousalData) {
                            editor.loadItems(tmpCarousalData);
                            newObj.content.carouselImages = tmpCarousalData;
                            tmpCarousalData = null;
                        } else {
                            editor.loadItems([]);
                        }

                        $scope.data = newObj;
                    }
                    tmrDelay = setTimeout(function () {
                        saveData(newObj);
                    }, 500);
                };

                var getPluginsIds = function (plugins) {
                    var pluginsIds = [];
                    for (var i = 0; i < plugins.length; i++) {
                        pluginsIds.push(plugins[i].instanceId);
                    }
                    return pluginsIds;
                }

                // this method will be called when a new item added to the list
                editor.onDeleteItem = editor.onItemChange = editor.onOrderChange = function () {

                    $scope.data.content.carouselImages = editor.items;
                    Utility.digest($scope);
                };

                editor.onAddItems = function (items) {
                    tmpCarousalData = items;
                    $scope.data.content.carouselImages = editor.items;
                    Utility.digest($scope);
                }

                plugins.onAddItems = function () {
                    var scopeItems = $scope.data._buildfire.plugins.data;
                    var itemIds = getPluginsIds(plugins.items);
                    for (var i = 0; i < itemIds.length; i++) {
                        if (scopeItems.indexOf(itemIds[i]) == -1) {
                            scopeItems.push(itemIds[i]);
                        }
                    }

                    Utility.digest($scope);
                };

                plugins.onDeleteItem = function (item, index) {
                    if (plugins.items.length == 0) {
                        $scope.data._buildfire.plugins.data = [];
                    } else {
                        $scope.data._buildfire.plugins.data.splice(index, 1);
                    }

                    Utility.digest($scope);
                };

                plugins.onOrderChange = function (item, oldIndex, newIndex) {
                    var items = $scope.data._buildfire.plugins.data;

                    var tmp = items[oldIndex];

                    if (oldIndex < newIndex) {
                        for (var i = oldIndex + 1; i <= newIndex; i++) {
                            items[i - 1] = items[i];
                        }
                    } else {
                        for (var i = oldIndex - 1; i >= newIndex; i--) {
                            items[i + 1] = items[i];
                        }
                    }

                    items[newIndex] = tmp;

                    $scope.data._buildfire = {
                        "plugins": {
                            "dataType": "pluginInstance",
                            "data": items
                        }
                    };

                    Utility.digest($scope);
                };

                plugins.onLoadAll = function () {
                    $scope.data.content.loadAllPlugins = true;

                    $("#plugins").find(".carousel-items").hide();
                    Utility.digest($scope);
                };

                plugins.onUnloadAll = function (items) {
                    $scope.data.content.loadAllPlugins = false;
                    $("#plugins").find(".carousel-items").show();
                    Utility.digest($scope);
                };

                var digest = function () {
                    if (!$scope.$$phase && !$scope.$root.$$phase) {
                        $scope.$apply();
                    }
                };
            }

        ]);
})(window.angular);