angular
        .module('carfriend')
        .controller('ProfileCtrl', ProfileCtrl);

function ProfileCtrl($stateParams, AuthService, $state, LoadingService, CarService, ColorService, $scope) {
    var vm = this;

    vm.car = {};
    vm.data = {};
    vm.goBack = goBack;
    vm.loadProfile = loadProfile;


    $scope.$on("$ionicView.beforeEnter", function () {
        console.log(AuthService.getUser().details.id, $stateParams.userID)
        if(AuthService.getUser().details.id === parseInt($stateParams.userID))
            vm.isItMe = true;
        else
            vm.isItMe = false;
        loadProfile();
    });
    
    //////////////


    function goBack() {
        if($stateParams.from)
           return $state.go($stateParams.from);
       else
           $state.go('tab.wildshield');
    }

    function loadProfile() {
       var user = {};
       LoadingService.startLoad();
        AuthService.fetch($stateParams.userID).then(function (user) {
            user = user.data;
            if (user.userType === 'driver')
                CarService.getUserCars($stateParams.userID).then(function (car) {
                    vm.data = car;
                    vm.data.userType = "driver";
                    vm.data.trust = user.trust;
                    vm.iconcolor = ColorService.getColors()[car.color];
                    if (LoadingService.isLoadingNow)
                        LoadingService.completeLoad();
                    console.log(vm.data);
                });
            else {
                vm.data.userType = "user";
                vm.data = user;
                if (LoadingService.isLoadingNow)
                    LoadingService.completeLoad();
            };
        });
    }
    ;
}
;