angular.module('stoute.wordpress', [])

    .service('WordPress',['$http','$q','$window',function($http,$q,$window){
        $window.wp = $window.wp || {};
        // defaults
        this.domain = "www.streamer.nl/wordpress";
        this.path_to_templates = "app/components/lib/views/";
        this.path_to_theme = '';
        this.static = false;
        this.model = {};
        this.model.pids = this.menus = this.params = {};

        this.init = function(options){
            var deferred = $q.defer();
            var _this = this;
            this.version = options.version || '3.19';
            this.domain = options.domain || this.domain;
            this.static = options.static || this.static;
            this.path_to_theme = options.path_to_theme || this.path_to_theme;
            this.path_to_templates = options.path_to_templates || this.path_to_templates;
            this.base_path = options.base_path || '/';
            this.protocol = options.protocol || 'http:';
            this.baseUrl = this.protocol + '//' + this.domain + this.base_path;
            this.restBaseUrl =  this.baseUrl;
            $http.get(this.restBaseUrl+'api/params/get_params/').then(function(result){
                _this.params = result.data;
                _this.ready = true;
                deferred.resolve(result.data);
            });
            return deferred.promise;
        };

        this.fetch = function(queryString){
            var deferred = $q.defer();
            var query = '?json=get_recent_posts';
            if(queryString){
                query = queryString + '?json=1';
            }
            $http.get(this.restBaseUrl+query).then(function(result){
                deferred.resolve(result.data);
            });
            return deferred.promise;
        };
        this.getPost = function(pid){
            var deferred = $q.defer();
            var _this=this;
            if(this.model.pids[pid] && this.static == true){
                deferred.resolve(this.model.pids[pid]);
            }else{
                $http.get(this.restBaseUrl+'?json=1&p='+pid).then(function(result){
                    _this.model.pids[result.data.post.id]=result.data.post;
                    deferred.resolve(result.data.post);
                });
            }
            return deferred.promise;
        };
        this.getCollection = function(collection){
            var deferred = $q.defer();
            var _this=this;
            var parse = function(list){
                angular.forEach(list,function(post){
                    _this.model.pids[post.ID]=post;
                });
                deferred.resolve(list);
            };
            $http.get(this.restBaseUrl+'?json=get_posts&post_type='+ collection).then(function(list){
                _this.model[collection] = list.data.posts;
                parse(list.data.posts);
            });
            return deferred.promise;
        };
        this.getMenu = function(mid){ // fixme:
            var deferred = $q.defer();
            var _this = this;
            $http.get(this.restBaseUrl+'api/menus/get_menu/?menu_id='+mid+'/').then(function(result){
                _this.menus[mid]=result.data.menu;
                deferred.resolve(result.data.menu);
            });
            return deferred.promise;
        };
        this.getMenus = function(){
            var deferred = $q.defer();
            var _this = this;
            var mids = [];
            var i = 0;
            angular.forEach(this.params.menus, function (menu) {
                mids.push(menu.term_id);
            });
            angular.forEach(mids, function (mid) {
                _this.getMenu(mid).then(function(menu){
                    _this.menus[mid] = menu;
                    i++;
                    if(i===mids.length){
                        deferred.resolve(_this.menus);
                    }
                })
            });
            return deferred.promise;
        }
    }])

    .controller('WorpressPostController',['$scope','$element','$attrs','WordPress' ,function($scope,$element,$attrs,WordPress) {
        $scope.getPost = function(pid){
            WordPress.getPost(pid).then(function(post){
                $scope.post = post;
            })
        };
        $scope.$watch($scope.pid,function(){ // fixme: dynamic loading
            $scope.getPost($scope.pid)
        });
        if($scope.pid){
            $scope.getPost($scope.pid)
        }
    }])
    .directive('wpPost',function() {
        return {
            restrict: 'E',
            scope: {
                pid:'='
            },
            controller: "WorpressPostController",
           // templateUrl: WordPress.path_to_templates+"wordpress-post.tpl.html"
            template: '<div class="clearfix type {{ post.type }}" id="post-{{ post.id }}" data-pid="{{ post.id }}" data-type="{{ post.type }}">' +
            '   <h3 class="title" >{{ post.title }}</h3>' +
            '   <div class="content" ng-bind-html="post.content | trustAsHtml"></div>'+
            '</div>'
        };
    })

    .directive('wpMenu', [ function () {
        //usage:  <wordpress-menu data="menus[mainMenu]" base="#/p/" depth="1"></wordpress-menu>
        return {
            restrict: "E",
            scope: { data: "=", base: "@", depth: "@" },
            controller: ['$scope', function ($scope) {
                $scope.$watch('data', function () {
                    if ($scope.data === undefined) {return;}
                    $scope.depth = $scope.depth || 1;
                    $scope.tree = [];
                    angular.forEach($scope.data, function (item) {
                        item.children = [];
                        if (item.parent_id == "0") {
                            $scope.tree.push(item);
                        }
                    });
                    angular.forEach($scope.data, function (item) {
                        if (item.parent_id != "0") {
                            angular.forEach($scope.tree, function (root) {
                                if(root.id==item.parent_id){
                                    root.children.push(item);
                                }
                            })
                        }
                    });
                });
            }],
            replace:true,
            template: '<li ng-repeat="item in tree" ng-class="menu-item"><a href="{{base}}{{item.object_id}}">{{item.label}}</a>' +
                '<span ng-show="depth > 1"><ul><li ng-repeat="item in item.children" ng-class="menu-item"><a href="{{base}}{{item.object_id}}">{{item.label}}</a></li></ul></span>' +
                '</li>'

        }
    }])

;
