angular.module('lcboApp.services')
    .factory('$ionicOverlay', ['$rootScope', '$document', '$compile', function($rootScope, $document, $compile) {
        return {
            /**
             * Load an action sheet with the given template string.
             *
             * A new isolated scope will be created for the
             * action sheet and the new element will be appended into the body.
             *
             * @param {object} opts the options for this ActionSheet (see docs)
             */
            show: function(opts) {
                var defaults = {
                    content: '',
                    animation: 'fade-in',
                    showBackdrop: true,
                    maxWidth: 200,
                    showDelay: 2000,
                    click: {}
                };

                opts = angular.extend(defaults, opts);

                var scope = $rootScope.$new(true);
                angular.extend(scope, opts);

                // Make sure there is only one loading element on the page at one point in time
                var existing = angular.element($document[0].querySelector('.loading-backdrop'));
                if(existing.length) {
                    existing.remove();
                }

                // Compile the template
                var element = $compile('<loading>' + opts.content + '</loading>')(scope);

                $document[0].body.appendChild(element[0]);

                var loading = new ionic.views.Loading({
                    el: element[0],
                    maxWidth: opts.maxWidth,
                    showDelay: opts.showDelay
                });

                loading.show();

                scope.close = opts.close;
                scope.loading = loading;

                return loading;
            }
        };
    }]);