
var tripapp = angular.module('tripapp', ['ngRoute', 'tripappControllers']);

var appUrl = '';
  
//tripapp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider)
tripapp.config(['$routeProvider', function($routeProvider)
{
    $routeProvider.
    when('/login/', {
        templateUrl: appUrl + 'partials/login.html',
        controller: 'Login'
    }).
    when('/dashboard/', {
        templateUrl: appUrl + 'partials/dashboard.html',
        controller: 'Dashboard'
    }).
    when('/trip/:tripID/', {
        templateUrl: appUrl + 'partials/trip.html',
        controller: 'TripController'
    }).
    otherwise({
        redirectTo: '/'
    });

    //$locationProvider.html5Mode(true);
}]);


var tripappControllers = angular.module('tripappControllers', []);

tripappControllers.controller('AppController', function($scope, $route, $location, $http, $window)
{
    $scope.active = false;
    
    $scope.checkUserActive = function(token)
    {
        $http(
        {
            method: 'GET',
            url: '/Trip/index.php/api/v1/auth',
            data: $.param(token),
            headers: { 
                'Content-Type': 'application/x-www-form-urlencoded',
                'Token': token
            }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                    // Reroute to Dashboard
                    $location.path('/dashboard');
                }
                else
                {
                    console.log(data.errors);

                    // Reroute to Login Page
                    $location.path('/login');
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.init = function()
    {
        // Check if a token
        if($window.sessionStorage.tripapptoken)
        {
            // Check token is valid
            console.log("Token is valid");
            $scope.checkUserActive($window.sessionStorage.tripapptoken);            
        }
        else
        {
            console.log("No Token found");
            // Reroute to Login Page
            $location.path('/login');
        }
    }

    $scope.init();

});

tripappControllers.controller('Login', function($scope,$http, $location, $window)
{
    console.log('Login Controller available');

    $scope.processLoginData = function(credentials)
    {
        // Reset Messages
        $scope.messagePassword = '';

        if(credentials) $scope.checkUserCredentials(credentials);
    }

    $scope.runDemo = function()
    {
        // Reset Messages
        $scope.messagePassword = '';

        var credentials = {
            email: 'help@andrewcobley.co.uk',
            password: 'tripdemo'
        };

        if(credentials) $scope.checkUserCredentials(credentials);
    }

    $scope.checkUserCredentials = function(credentials)
    {
        $http(
        {
            method: 'POST',
            url: '/Trip/index.php/api/v1/login',
            data: $.param(credentials),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    $window.sessionStorage.tripapptoken = data.success;
                    $http.defaults.headers.common['Token'] =  $window.sessionStorage.tripapptoken;

                    console.log($window.sessionStorage);
                    
                    console.log("DEMO? - " + data.demo);

                    if(data.demo == true)
                    {
                        console.log("Reroute to Demo Trip: " + data.demo_trip);   
                        // Reroute to Demo Trip
                        $location.path('/trip/' + data.demo_trip + '/');
                    }
                    else
                    {
                        console.log("Reroute to Dashboard");   
                        // Reroute to Dashboard
                        $location.path('/dashboard');
                    }
                }
                else
                {
                    console.log(data.errors);
                    if(data.errors) $scope.messagePassword = data.errors;
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }
});

tripappControllers.controller('Dashboard', function($scope, $routeParams, $http, $window)
{ 
    //$scope.username = $routeParams.username;
    //console.log($scope.username);

    console.log('Dashboard Controller available');

    $scope.trips = {};

    $scope.getTripsForUser = function()
    {
        $http({ method: 'GET',
            url: '/Trip/index.php/api/v1/trip/user',
            headers: { 
                'Content-Type': 'application/x-www-form-urlencoded',
                'Token': $window.sessionStorage.tripapptoken
            }
        }).
            success(function(data, status, headers, config)
            {
                console.log(data);
                $scope.trips = data;
            }).
            error(function(data, status, headers, config)
            {
                console.log(data);
            }
        );
    }

    $scope.getTripsForUser();

});

tripappControllers.controller('TripController', function($scope, $routeParams, $http, $window)
{
    console.log('Trip Controller available');

    $http.defaults.headers.common['Token'] =  $window.sessionStorage.tripapptoken;

    $scope.id = $routeParams.tripID;
    console.log($scope.id);

    $scope.trip;

    console.log($window.sessionStorage);

    $scope.getTripDirectory = function(id, mapReset)
    {

        $http({ method: 'GET',
                url: '/Trip/index.php/api/v1/trip/'+id+'/directory',
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
        }).
            success(function(data, status, headers, config)
            {
                $scope.trip = data.trip;

                if(mapReset)
                {
                    setMapForTrip(data.trip);
                    setupDirectory();
                    openSideMenu();
                }

                $scope.updateTypeList();
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.getTripDirectory($scope.id,true);

    $scope.$on('refreshTripMenu', function()
    {
        if($scope.trip) $scope.getTripDirectory($scope.trip.id,false);
    });

    $scope.updateTypeList = function()
    {
        $scope.trip.types = [];

        if( $scope.trip.areas[0] )
        {
            angular.forEach($scope.trip.areas[0].types, function(value, key)
            {
                $scope.trip.types.push({
                    id: value['id'],
                    name: value['name']
                });
            });
        }
        console.log($scope.trip.types);
    }

    $scope.numberOfType = function()
    {
        var count = 0;
        angular.forEach($scope.trip.areas.types.places, function() {
            count += todo.done ? 0 : 1;
        });
        return count;
    };

    $scope.deleteArea = function(id)
    {
        $http({ method: 'DELETE',
                url: '/Trip/index.php/api/v1/trip/'+$scope.id+'/area/'+id,
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
        }).
            success(function(data, status, headers, config)
            {
                console.log(data);
                $scope.getTripDirectory($scope.id,false);
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.deletePlace = function(id)
    {
        $http({ method: 'DELETE',
                url: '/Trip/index.php/api/v1/trip/'+$scope.id+'/place/'+id,
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
        }).
            success(function(data, status, headers, config)
            {
                console.log(data);
                $scope.getTripDirectory($scope.id,false);
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }
});


// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// > PLACE ENTRY CONTROLLER

//tripappControllers.controller('PlaceEntry', function($scope, $http, $window)
function PlaceEntry($scope, $http, $window)
{
    $http.defaults.headers.common['Token'] =  $window.sessionStorage.tripapptoken;

    $scope.getPlaceEntryForID = function(id)
    {
        $http({method: 'GET', url: '/Trip/index.php/api/v1/place/'+id+'/all'}).
            success(function(data, status, headers, config)
            {
                $scope.place = data.place;
                showPlaceInfo();
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }
}

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// > ADD AREA CONTROLLER

//tripappControllers.controller('AddArea', function($scope, $http, $window)
function AddArea($scope, $http, $window)
{
    $http.defaults.headers.common['Token'] =  $window.sessionStorage.tripapptoken;

    $scope.area = {};

    $scope.processAreaData = function()
    {
        $scope.area.trip_id = $scope.trip.id;
        //console.log('Process Area Data');
        //console.log($scope.areaData);
        $scope.createNewArea();
    }

    $scope.createNewArea = function(area)
    {
        $http(
        {
            method: 'POST',
            url: '/Trip/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/area',
            data: $.param($scope.area),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    newAreaAdded();
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.trip_id) $scope.messageTrip = data.errors.trip_id[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }

    $scope.reset = function(area)
    {
        $scope = {};
    }
}


// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// > ADD PLACE CONTROLLER

//tripappControllers.controller('AddPlace', function($scope, $http, $window)
function AddPlace($scope, $http, $window)
{
    $http.defaults.headers.common['Token'] =  $window.sessionStorage.tripapptoken;

    $scope.place = {};
    $scope.place.location = {};
    $scope.place.links = [];
    $scope.place.attachments = [];

    $scope.processPlaceData = function()
    {
        //console.log($scope.place);
        $scope.createNewPlace();
    }

    $scope.updatePlaceGeoCoords = function(geolat, geolng)
    {
        $scope.$apply(function()
        {
            $scope.place.location.geolat = geolat;
            $scope.place.location.geolng = geolng;
        });
    }

    $scope.createNewPlace = function(area)
    {
        console.log($scope.place);
        $http(
        {
            method: 'POST',
            url: '/Trip/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/place',
            data: $.param($scope.place),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    //console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    newPlaceAdded(data.success);
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.area) $scope.messageArea = data.errors.area[0];
                    if(data.errors.type) $scope.messageType = data.errors.type[0];
                    if(data.errors.location) $scope.messageLocation = data.errors.location[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }

    $scope.addLink = function()
    {
        var id = $scope.linkID;
        $scope.linkID++;

        $scope.place.links.push( 
        {
            id: id,
            name: '',
            address: ''
        });

    }

    $scope.removeLink = function(id)
    {
        angular.forEach($scope.place.links, function(link, key)
        {
            if(link.id === id)
            {
                $scope.place.links.splice(key,1);
            }
        });
    }

    $scope.attachmentID = 0;

    $scope.addAttachment = function()
    {
        var id = $scope.attachmentID;
        $scope.attachmentID++;

        $scope.place.attachments.push( 
        {
            id: id,
            name: '',
            address: ''
        });
    }

    $scope.removeAttachment = function(id)
    {
        angular.forEach($scope.place.attachments, function(attachment, key)
        {
            if(attachment.id === id)
            {
                //console.log(key);
                $scope.place.attachments.splice(key,1);
            }
        });
    }

    $scope.reset = function(area)
    {
        $scope = {};
    }
}


// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// > EDIT AREA CONTROLLER

//tripappControllers.controller('EditArea', function($scope, $http, $window)
function EditArea($scope, $http, $window)
{
    $http.defaults.headers.common['Token'] =  $window.sessionStorage.tripapptoken;

    $scope.area = {};

    $scope.setupEditForArea = function(id)
    {
        //console($http.defaults.headers);

        $http({method: 'GET', url: '/Trip/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/area/'+id }).
            success(function(data, status, headers, config)
            {
                $scope.area = data.area;
                console.log($scope.area);
                areaEditSetupComplete();
            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
                console.log(headers);
            }
        );
    }

    $scope.processAreaData = function()
    {
        $scope.editAreaWithData();
    }

    $scope.editAreaWithData = function()
    {
        $http(
        {
            method: 'PATCH',
            url: '/Trip/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/area',
            data: $.param($scope.area),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    areaEditComplete();
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.trip_id) $scope.messageTrip = data.errors.trip_id[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }

    $scope.reset = function(area)
    {
        //$scope = {};
    }
}


// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// > EDIT PLACE CONTROLLER

//tripappControllers.controller('EditPlace', function($scope, $http, $window)
function EditPlace($scope, $http, $window)
{
    $http.defaults.headers.common['Token'] =  $window.sessionStorage.tripapptoken;

    $scope.place = {};
    $scope.original = {};

    $scope.setupEditForPlace = function(id)
    {
        console.log(id);
        $scope.place.id = id;
        $http({method: 'GET', url: '/Trip/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/place/'+id }).
            success(function(data, status, headers, config)
            {
                $scope.place = data.place;

                console.log(data);

                // Record Original Place Location
                $scope.original.geolat = $scope.place.location.geolat;
                $scope.original.geolng = $scope.place.location.geolng;

                // Run Additional Functions when Conplete
                placeEditSetupComplete(id);

            }).
            error(function(data, status, headers, config)
            {
                console.log(status);
            }
        );
    }

    $scope.processPlaceData = function()
    {
        //console.log($scope.place);
        $scope.editPlaceWithData();
    }

    $scope.updatePlaceGeoCoords = function(geolat, geolng)
    {
        $scope.$apply(function()
        {
            $scope.place.location.geolat = geolat;
            $scope.place.location.geolng = geolng;
        });
    }

    $scope.editPlaceWithData = function()
    {
        console.log($scope.place);
        $http(
        {
            method: 'PATCH',
            url: '/Trip/index.php/api/v1/trip/'+$scope.$parent.trip.id+'/place',
            data: $.param($scope.place),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
            success(function(data, status, headers, config)
            {
                if(data.success)
                {
                    console.log(data.success);
                    $scope.$emit('refreshTripMenu');
                    placeEditComplete($scope.place.id);
                }
                else
                {
                    if(data.errors.name) $scope.messageName = data.errors.name[0];
                    if(data.errors.area) $scope.messageArea = data.errors.area[0];
                    if(data.errors.type) $scope.messageType = data.errors.type[0];
                    if(data.errors.location) $scope.messageLocation = data.errors.location[0];
                }
            }).
            error(function(data, status, headers, config)
            {
                console.log("Connection Error");
            }
        );
    }

    $scope.addLink = function()
    {
        var id = $scope.linkID;
        $scope.linkID++;

        $scope.place.links.push( 
        {
            id: id,
            name: '',
            address: ''
        });

    }

    $scope.removeLink = function(id)
    {
        angular.forEach($scope.place.links, function(link, key)
        {
            if(link.id === id)
            {
                $scope.place.links.splice(key,1);
            }
        });
    }

    $scope.attachmentID = 0;

    $scope.addAttachment = function()
    {
        var id = $scope.attachmentID;
        $scope.attachmentID++;

        $scope.place.attachments.push( 
        {
            id: id,
            name: '',
            address: ''
        });
    }

    $scope.removeAttachment = function(id)
    {
        angular.forEach($scope.place.attachments, function(attachment, key)
        {
            if(attachment.id === id)
            {
                //console.log(key);
                $scope.place.attachments.splice(key,1);
            }
        });
    }

    $scope.reset = function(area)
    {
        //$scope = {};
    }
}


