// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
var db;
angular.module('starter', ['ionic', 'ngCordova', 'ngCordovaOauth',  'starter.controllers'])
.run(function($ionicPlatform, $cordovaSQLite) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
	if (window.cordova) {
	    try {
	        db = $cordovaSQLite.openDB({
	            name: "tna.db",
	            location: 'default'
	        });
	    } catch (error) {
	        alert(error);
	    }
	    $cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS Messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT)');
	    $cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS Personal(key TEXT PRIMARY KEY, value TEXT)');
	}
 });
})
.filter('humanize', function(){
    return function humanize(number) {
        if(number < 1000) {
            return number;
        }
        var si = ['K', 'M', 'G', 'T', 'P', 'H'];
        var exp = Math.floor(Math.log(number) / Math.log(1000));
        var result = number / Math.pow(1000, exp);
        result = (result % 1 > (1 / Math.pow(1000, exp - 1))) ? result.toFixed(2) : result.toFixed(0);
        return result + si[exp - 1];
    };
})
.filter('get_url', ['IMG_URI', function(IMG_URI){
    return function(url) {
        return IMG_URI + url;
    };
}])
.filter('map_link',[function(){
    return function(geocode) {
        var isIOS = ionic.Platform.isIOS();
        var isAndroid = ionic.Platform.isAndroid();
        if( isIOS ) {
            return "maps://?q="+geocode;
        }
        if( isAnroid ) {
            return "geo:"+geocode;
        }
    };
}])
.filter('titleCase', function() {
    return function(input) {
      input = input || '';
      return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    };
  })
.filter('get_last_array', function(){
    return function(arr) {
        if( arr.length > 0 ){
            var v  = arr[arr.length-1];
            if( v == ""){
                return "Untitled";
            }else {
                return v;
            }
        } else
            return "Untitled";
    };
})
.value('THROTTLE_MILLISECONDS', 4000)
//.constant('API_URI', 'http://localhost:5050')
.constant('API_URI', 'http://mcotn-api.simplico.net')
//.constant('IMG_URI', 'http://simplico.net:5060')
.constant('IMG_URI', 'http://mcotn-backend.simplico.net')
//.constant('GEN_USER_API_URI', 'http://localhost:5052')
.constant('GEN_USER_API_URI', 'http://mcotn-simplitic.simplico.net')
.constant('SEARCH_API', '/api/v1.0/search?collection=posts')
.constant('SHARE_API', '/api/v1.0/share')
.constant('USER_API', '/api/v1.0/users_social')
.constant('CMS_USER_API', '/api/v1.0/users')
.constant('SETTING_API', '/api/v1.0/setting')
.constant('FAV_API', '/api/v1.0/fav')
.constant('NOTI_API', '/api/v1.0/noti')
.constant('AUTH_API', '/auth')
.constant('PAGE_LIMIT', 10)
.constant('DB', 'lively.db')
.constant('PUBLIC_TOKEN', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoicHVibGljIiwicm9sZXMiOlsicHVibGljIl0sImV4cCI6MTczNDE2NTcxMCwiaWF0IjoxNDc0OTY1NzEwLCJuYmYiOjE0NzQ5NjU3MTAsImlkZW50aXR5IjoiNTdlOWVmMjZjMjU0ZmQ4N2Q3ZmQ4MzM2In0.-9fcm5s8qYbdqBDUX7cZJ5J3AX91fe6VrCLs_S-_eBU')
.config(function($stateProvider, $urlRouterProvider, $cordovaInAppBrowserProvider, $ionicConfigProvider) {
  var defaultOptions = {
      location: 'no',
      clearcache: 'no',
      toolbar: 'yes'
  };
$ionicConfigProvider.backButton.previousTitleText(false).text('');
  $cordovaInAppBrowserProvider.setDefaultOptions(defaultOptions);
 $stateProvider

    .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
    controller: 'AppCtrl'
  })

  .state('app.search', {
    url: '/search',
    views: {
      'menuContent': {
        templateUrl: 'templates/search.html',
        controller: 'SearchCtrl'
      }
    }
  })

  .state('app.login', {
    url: '/login',
    views: {
        'menuContent': {
            templateUrl: 'templates/login.html',
            controller: 'LoginCtrl'
        }
    }
  })
  .state('app.view', {
    url: '/view/:id',
    views: {
      'menuContent': {
        templateUrl: 'templates/view.html',
        controller: 'ViewCtrl'
      }
    }
  })

  .state('app.browse', {
      url: '/browse',
      views: {
        'menuContent': {
          templateUrl: 'templates/browse.html'
        }
      }
    })
    .state('app.playlists', {
      url: '/playlists',
      views: {
        'menuContent': {
          templateUrl: 'templates/playlists.html',
          controller: 'PlaylistsCtrl'
        }
      }
    })
    .state('app.settings', {
      url: '/settings',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/settings.html',
          controller: 'SettingCtrl'
        }
      }
    })

    .state('app.index', {
      url: '/index',
      views: {
        'menuContent': {
          templateUrl: 'templates/index_page.html',
          controller: 'IndexPageCtrl'
        }
      }
    })
    .state('app.fav', {
      url: '/fav',
      cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/index_page.html',
          controller: 'FavCtrl'
        }
      }
    })
    .state('app.byauthor', {
        url: '/byauthor/:uid',
      views: {
        'menuContent': {
          templateUrl: 'templates/byauthor.html',
          controller: 'ByAuthorCtrl'
        }
      }
    })
    .state('app.cat', {
        url: '/cat/:catname',
      views: {
        'menuContent': {
          templateUrl: 'templates/index_page.html',
          controller: 'ListPageCtrl'
        }
      }
    })
    .state('app.nearby', {
        url: '/nearby',
        cache: false,
      views: {
        'menuContent': {
          templateUrl: 'templates/nearby.html',
          controller: 'NearbyCtrl'
        }
      }
    })

  .state('app.single', {
    url: '/playlists/:playlistId',
    views: {
      'menuContent': {
        templateUrl: 'templates/playlist.html',
        controller: 'PlaylistCtrl'
      }
    }
  });
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/index');
})
.service('mcotcms', function($http, $httpParamSerializer, API_URI, SEARCH_API, PAGE_LIMIT, SHARE_API, USER_API,GEN_USER_API_URI, AUTH_API, $cordovaSQLite, SETTING_API, FAV_API, NOTI_API, CMS_USER_API) {

    this.all_posts = function(){
        console.log("all posts");
		return $http({
            method: 'GET',
            url: API_URI + SEARCH_API
		});
    }
    this.get_share = function(id){
        var params = {
            'id': id,
            'action': 'FETCH'
        };

        var qs = $httpParamSerializer(params);
		return $http({
            method: 'POST',
            url: GEN_USER_API_URI + SHARE_API,
            data: params
		});
    }
    this.update_share = function(id){
        var params = {
            'id': id,
            'action': 'update'
        };

        var qs = $httpParamSerializer(params);
		return $http({
            method: 'POST',
            url: GEN_USER_API_URI + SHARE_API,
            data: params
		});
    }
    this.clear_data = function(){
        console.log("clear data");
        window.localStorage.clear();

    }
    this.load_data = function(){
	    return $cordovaSQLite.execute(db, 'SELECT * FROM Messages ORDER BY id DESC');
    }
    this.load_personal_data = function(key){
	    return $cordovaSQLite.execute(db, 'SELECT *  FROM Personal where key = ?', [key]);
    }
    this.get_settings = function(token){
        var params = {
            action: 'GET'
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + SETTING_API,
            headers: {
                Authorization: 'JWT '+token,
            },
            data: params
        });
    }
    this.post_api = function(token, action, model){
        var params = {
            'model': model,
            'action': action
        };
        return $http({
            method: 'POST',
            url: API_URI + "/api/v2.0/posts",
            headers: {
                Authorization: 'JWT '+token,
            },
            data: params
        });
    }
    this.by_author = function(author_id){
        var params = {
            'id': author_id,
        };
        var qs = $httpParamSerializer(params);
		return $http({
            method: 'GET',
            url: API_URI + CMS_USER_API + "?id=" + author_id,
            data: params
		});
    }
    this.more_on = function(oid, options){
        var params = {
            'method': 'moreon',
            'id': oid,
            /*
            'query': {
                'meta.location': {
                    '$near': {
                        '$geometry': {'type': "Point", 'coordinates':  [position.longitude, position.latitude]},
                        '$maxDistance': 5000
                    }
                }
            },*/
            'type': options.type,
            'version': 'short'

        };
        var qs = $httpParamSerializer(params);
		return $http({
            method: 'POST',
            url: API_URI + SEARCH_API,
            data: params
		});
    }
    this.nearby = function(position, options){
        var page = options.page;
        var skip = page * PAGE_LIMIT;
        var limit = PAGE_LIMIT;
        var params = {
            'query': {
                'location': {
                    '$near': {
                        '$geometry': {'type': "Point", 'coordinates':  [position.longitude, position.latitude]},
                        '$maxDistance': 5000
                    }
                }
            },
            'type': options.type,
            'skip': skip,
            'page': page,
            'limit': limit,
            'version': 'short'

        };
        var qs = $httpParamSerializer(params);
		return $http({
            method: 'POST',
            url: API_URI + SEARCH_API,
            data: params
		});
    }
    this.save_settings = function(token, cats){
        var params = {
            'cats': cats,
            'action': 'UPDATE'
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + SETTING_API,
            headers: {
                Authorization: 'JWT '+token,
            },
            data: params
        });
    }
    this.get_fav  = function(token, options){

        var page = options.page;
        var skip = page * PAGE_LIMIT;
        var limit = PAGE_LIMIT;
        var params = {
            'action': 'GET',
            'type': options.type,
            'skip': skip,
            'page': page,
            'limit': limit
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + FAV_API,
            headers: {
                Authorization: 'JWT '+token,
            },
            data: params
        });
    }
    this.fetch_noti = function(token, options) {
        var params = {
            'action': 'FETCH',
            'type': options.type,
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + NOTI_API,
            headers: {
                Authorization: 'JWT '+token,
            },
            data: params
        });
    }
    this.add_fav = function(token, post_id, type){
        var params = {
            'post_id': post_id,
            'action': 'ADD',
            'type': type
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + FAV_API,
            headers: {
                Authorization: 'JWT '+token,
            },
            data: params
        });
    }
    this.store_token = function(token){
        var storage = window.localStorage;
        console.log("token is ", token);
        storage.setItem("token", token);
        return $cordovaSQLite.execute(db, 'INSERT or REPLACE INTO Personal(key, value) VALUES (?, ?)', ['token', token]);
    }

    this.get_token  = function(){
        return window.localStorage.getItem("token");
    }
    this.get_post_by_id = function(id){

        var params = {
            'id': id,
            'version': 'full'
        };
        var qs = $httpParamSerializer(params);
		return $http({
            method: 'POST',
            url: API_URI + SEARCH_API,
            data: params
		});
    }

    this.login = function(username, pass) {

        var params = {
            'username': username,
            'password': pass
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + AUTH_API,
            data: params
        });
    }
    this.add_user = function(user_obj){
        var params = {
            'obj': user_obj,
            'action': 'add'
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + USER_API,
            data: params
        });
    }
    this.add_user_by_form = function(user_obj){
        var params = {
            'obj': user_obj,
            'action': 'register_by_form'
        };
        var qs = $httpParamSerializer(params);
        return $http({
            method: 'POST',
            url: GEN_USER_API_URI + USER_API,
            data: params
        });
    }
    this.get_posts = function(option) {
        var query = option.query;
        var page = option.page;
        var skip = page * PAGE_LIMIT;
        var limit = PAGE_LIMIT;
        var version = option.version;
        var params = {
            'query': query,
            'page': page,
            'skip': skip,
            'limit': limit,
            'version': version,
			'sort': 'desc'
        };
        var qs = $httpParamSerializer(params);
        console.log(qs);
		return $http({
            method: 'POST',
            url: API_URI + SEARCH_API,
            data: params
		});
    }

})
.directive('searchBar', [function () {
	return {
		scope: {
			ngModel: '='
		},
		require: ['^ionNavBar', '?ngModel'],
		restrict: 'E',
		replace: true,
		template: '<ion-nav-buttons side="right">'+
						'<div class="searchBar">'+
							'<div class="searchTxt" ng-show="ngModel.show">'+
						  		'<div class="bgdiv"></div>'+
						  		'<div class="bgtxt">'+
						  			'<input type="text" placeholder="Procurar..." ng-model="ngModel.txt">'+
						  		'</div>'+
					  		'</div>'+
						  	'<i class="icon placeholder-icon" ng-click="ngModel.txt=\'\';ngModel.show=!ngModel.show"></i>'+
						'</div>'+
					'</ion-nav-buttons>',

		compile: function (element, attrs) {
			var icon=attrs.icon
					|| (ionic.Platform.isAndroid() && 'ion-android-search')
					|| (ionic.Platform.isIOS()     && 'ion-ios7-search')
					|| 'ion-search';
			angular.element(element[0].querySelector('.icon')).addClass(icon);

			return function($scope, $element, $attrs, ctrls) {
				var navBarCtrl = ctrls[0];
				$scope.navElement = $attrs.side === 'right' ? navBarCtrl.rightButtonsElement : navBarCtrl.leftButtonsElement;

			};
		},
		controller: ['$scope','$ionicNavBarDelegate', function($scope,$ionicNavBarDelegate){
			var title, definedClass;
			$scope.$watch('ngModel.show', function(showing, oldVal, scope) {
				if(showing!==oldVal) {
					if(showing) {
						if(!definedClass) {
							var numicons=$scope.navElement.children().length;
							angular.element($scope.navElement[0].querySelector('.searchBar')).addClass('numicons'+numicons);
						}

						title = $ionicNavBarDelegate.getTitle();
						$ionicNavBarDelegate.setTitle('');
					} else {
						$ionicNavBarDelegate.setTitle(title);
					}
				} else if (!title) {
					title = $ionicNavBarDelegate.getTitle();
				}
			});
		}]
	};
}]);
