// TODO: Add 'info' item
// TODO: Test android (and ios again)
// ENHANCE: Add 'ads' item
// ENHANCE: Add 'raw_html' item

angular.module('starter.controllers', ['futbalapi', 'LocalStorageModule', 'ionic', 'ui.router'])
  .run(function ($rootScope, $ionicPlatform, localStorageService) {
    // Initialize local storage
    var favorites = localStorageService.get('favorites');

    $rootScope.isIos = false;

    if (!favorites ||  _.keys(favorites).length !== 4) {
      favorites = {
        'news' : [],
        'game' : [],
        'teams' : [],
        'social_media' : []
      };
    }

    $rootScope.openExternal = function (url) {

      if( 'firefoxos' === device.platform ) {
        window.open(url, '_blank');
      }else{
        window.open(url, '_system');
      }

    };

    localStorageService.set('favorites', favorites);

    // ios body classes
    if (ionic.Platform.isIOS() || ionic.Platform.isIPad()) {
      $rootScope.isIos = true;
    }
  })

  .controller('AppCtrl', function($scope, $rootScope, $state) {
    $rootScope.gotoData = function () {
      $state.go('app.data');
    }
  })

  .controller('DetailTeamCtrl', function ($scope, $rootScope, $state, $stateParams, TeamApi, FavoriteApi, localStorageService) {
    TeamApi.one($stateParams.id, function (team) {
      $scope.team = Futbal.enhanceTeamData(team, localStorageService.get('favorites'));

      $scope.team.matches = _.map($scope.team.matches, function (match) {
        return Futbal.enhanceMatchData(match, true);
      });

      $scope.team.standings = _.map($scope.team.standings, function (standings) {
        return Futbal.enhanceStandingsData(standings);
      });
    });

    $scope.favoriteAction = function () {
      this.team.type = 'teams';
      this.team = FavoriteApi.toggleFeedItem(this.team);

      if (this.team.favoriteClass == 'favorite') {
        this.team.favoriteClass = 'button-royal';
      }
    };

    $scope.goBack = function() {
      $rootScope.fromFavorites = false;
      $state.go('app.favorites');
    };
  })

  .controller('DetailMatchCtrl', function($scope, $rootScope, $state, $stateParams, MatchApi) {
    $scope.invalid = !$stateParams.id;

    $scope.doRefresh = function (now) {
      MatchApi.one($stateParams.id, function (match) {
        $scope.match = Futbal.enhanceMatchData(match);
        $scope.$broadcast('scroll.refreshComplete');
      }, now);
    };

    // Initialize the data
    $scope.doRefresh(false);

    $scope.goBack = function() {
      $rootScope.fromModal = false;
      $state.go('app.home');
    };
  })

  .controller('DataCtrl', function($rootScope, $scope, $ionicScrollDelegate, MatchApi, TeamApi) {
    if (!$rootScope.viewMode) {
      $rootScope.viewMode = 'matches';
    }

    MatchApi.all(function (matches) {
      $scope.matches = _.map(matches, function (match) {
        return Futbal.enhanceMatchData(match, true);
      });
    });

    TeamApi.all(function (teams) {
      $scope.teams = _.map(teams, function (team) {
        return Futbal.enhanceTeamData(team, {});
      });
    });

    $scope.toggleView = function (viewMode) {
      $ionicScrollDelegate.scrollTop(false);
      $rootScope.viewMode = viewMode;
    };

    $scope.isActivated = function () {
      return $rootScope.viewMode === 'matches';
    };
  })

  .controller('FavoriteCtrl', function ($scope, $rootScope, FeedApi, FavoriteApi, localStorageService, $ionicModal) {
    var favorites = localStorageService.get('favorites');

    $scope.noFeedFavorites = false;
    $scope.notLoaded = true;

    Futbal.initDetailItemModal($ionicModal, $scope, localStorageService, FavoriteApi, function ($scope) {
      $scope.modal.hide();
      // Also remove the favorites client side
      $scope.feedFavorites[$scope.detail.type] = _.reject(
        $scope.feedFavorites[$scope.detail.type],
        function(item) { return item.id === $scope.detail.id; }
      );

      var favorites = $scope.feedFavorites;

      if (favorites.social_media.length === 0 && favorites.news.length === 0) {
        $scope.noFeedFavorites = true;
      }
    });

    FeedApi.favorites(favorites, function (favorites) {
      favorites.teams = _.map(favorites.teams, function (team) {
        return Futbal.enhanceTeamData(team);
      });


      favorites.news = _.map(favorites.news, function (news) {
        return Futbal.enhanceItem(news);
      });

      $scope.feedFavorites = favorites;

      if (favorites.social_media.length === 0 && favorites.news.length === 0) {
        $scope.noFeedFavorites = true;
      }

      $scope.notLoaded = false;
    });

    $scope.linkAction = function () {
      $rootScope.fromFavorites = true;
    };
  })

  .controller('HomeCtrl', function($scope, $rootScope, $stateParams, FeedApi, FavoriteApi, localStorageService, $ionicModal) {
    $scope.isLoadingMore = false;

    $scope.doRefresh = function (now) {
      FeedApi.all(function (items) {
        var enhancedItems = [],
          favorites = localStorageService.get('favorites');

        _.each(items, function (item) {
          enhancedItems.push(Futbal.enhanceItem(item, favorites));
        });

        enhancedItems.splice(2,0, {
          'type': 'ad'
        });

        $scope.items = enhancedItems;

        $scope.$broadcast('scroll.refreshComplete');

        Inneractive.initVars();
        Inneractive.loadScript();

      }, null, now);
    };

    // Initialize with data
    $scope.doRefresh(false);

    $scope.shareAction = function (msg) {
      window.plugins.socialsharing.share(msg);
    };

    $scope.loadMore = function () {
      $scope.isLoadingMore = true;

      FeedApi.all(function (items) {
        var enhancedItems = [],
          favorites = localStorageService.get('favorites');

        _.each(items, function (item) {
          enhancedItems.push(Futbal.enhanceItem(item, favorites));
        });


        $scope.items = enhancedItems;



        $scope.isLoadingMore = false;
      }, $scope.items.length + 10);
    };


    // Detail View
    Futbal.initDetailItemModal($ionicModal, $scope, localStorageService, FavoriteApi, function () {}, $rootScope);

    $scope.favoriteAction = function () {
      this.item = FavoriteApi.toggleFeedItem(this.item);
    };
  })
;
