taxiApp.controller("hailController", function ($scope, hardcodedData, $log, $http, pickupService, $state, uiGmapGoogleMapApi, $timeout) {
    var isInit = false;
    $scope.initModel = function(){
        if(!isInit){
            $scope.model = pickupService.currentTripDetail;
            isInit = true;
        }
        $scope.model.partyName = "";
        $scope.model.partySize = "";
        $scope.model.phoneNumber = "";
    };
    $scope.canSubmit = false;
    $scope.hasSubmitted = false;

    $scope.canEstimate = function(){
        return $scope.model.partyName.length > 0 && $scope.model.partySize.length > 0 && $scope.phoneNumber.length > 0;
    };

    $scope.alerts = [];

    $scope.submit = function(){
        if (!$scope.canSubmit) {
            return;
        }
        $scope.canSubmit = false;
        $scope.requestPending = true;
        var payload = {
            PartySize: $scope.model.partySize,
            PartyName: $scope.model.partyName,
            PhoneNumber: $scope.model.phoneNumber,
            Pickup: {
                address: $scope.model.pickupLocation.address,
                geoLocation: $scope.model.pickupLocation.geoLocation,
                name: $scope.model.pickupLocation.friendlyName
            },
            Dropoff: {
                address: $scope.model.destinationLocation.address,
                geoLocation: $scope.model.destinationLocation.geoLocation,
                name: $scope.model.destinationLocation.friendlyName
            },
            ReserveTime: new Date()
        };

        $http.post(hardcodedData.baseApiUrl + "/HailCab/HailACab/", { tripRequest: payload })
            .then(function(data) {
                    $scope.alerts.push({
                        type: 'success',
                        msg: 'Your trip has been submitted.  A driver will call you at ' +
                        data.data.PhoneNumber +
                        "."
                    });
                    $scope.resetCanSubmit();
                    $scope.hasSubmitted = true;
                    $scope.requestPending = false;
                },
                function() {
                    $scope.alerts
                        .push({ type: 'danger', msg: 'An error occurred and we were unable to submit your trip.' });
                    $scope.resetCanSubmit();
                    $scope.requestPending = false;
                });

        $scope.calculateFare();
    };
    $scope.modelIsValid = function() {
        return $scope.hailModel.partySize !== "" && $scope.hailModel.partySize &&
            $scope.model.partyName !== "" && $scope.hailModel.partyName &&
            $scope.model.partyPhone !== "" && $scope.hailModel.partyPhone &&
            $scope.model.pickupTime !== "" && $scope.hailModel.pickupTime &&
            Object.keys($scope.hailModel.pickup).length > 0 &&
            Object.keys($scope.hailModel.dropoff).length > 0;
    };
    $scope.canSubmit = true;
    $scope.requestPending = false;
    $scope.resetCanSubmit = function() {
        $timeout(function() {
            $scope.canSubmit = true;
        }, 30000);
    };

    $scope.clear = function(){
        $scope.initModel();
    };

    $scope.cancel = function(){
        pickupService.resetTripDetail();
        $state.transitionTo("index");
    };

    $scope.calculateFare = function () {
        if ( pickupService.currentTripDetail.pickupPlace !== undefined && pickupService.currentTripDetail.destinationPlace !== undefined) {
            var directions = new $scope.mapsApi.DirectionsService();
            var payload = {
                origin: {'placeId' : pickupService.currentTripDetail.pickupPlace.place_id },
                destination: {'placeId' : pickupService.currentTripDetail.destinationPlace.place_id },
                travelMode: $scope.mapsApi.TravelMode.DRIVING,
                unitSystem: $scope.mapsApi.UnitSystem.IMPERIAL,
                optimizeWaypoints: false,
                provideRouteAlternatives: false,
                avoidHighways: false,
                avoidTolls: true,
                region: "US"
            };
            directions.route(payload, function (result, status) {
                if (status === $scope.mapsApi.DirectionsStatus.OK) {
                    if (!$scope.directionsDisplay) {
                        $scope.directionsDisplay = new google.maps.DirectionsRenderer();
                    }
                    $scope.directionsDisplay.setMap($scope.googleMap);
                    $scope.directionsDisplay.setDirections(result);
                    $scope.currentDirections = result;
                    $scope.miles = result.routes[0].legs[0].distance.value / 1609.34;
                    $scope.roundedMiles = (Math.round($scope.miles * 8) / 8).toFixed(2);
                    $scope.duration = result.routes[0].legs[0].duration.text;
                    $scope.fare = 3 + ($scope.roundedMiles * 3.20);
                    $scope.tripCalculated = true;
                }
            });
        }
    };

    $scope.closeAlert = function (index) {
        $scope.alerts.splice(index, 1);
    };

    $scope.map =
        {
            center:
                {
                    latitude: 19.653244500891283,
                    longitude: -155.87811279296875
                },
            zoom: 10,
            bounds:
                {
                    northeast:
                        {
                            latitude: 20.114091,
                            longitude: -155.220051
                        },
                    southwest:
                        {
                            latitude: 19.355323,
                            longitude: -156.490345
                        }
                },
            markers: [],
            events:
                {
                    tilesloaded: function (map, eventName, originalEventArgs) {
                        $scope.googleMap = map;
                    },
                    click: function (mapModel, eventName, originalEventArgs) {
                    }
                }
        };
    uiGmapGoogleMapApi.then(function (maps) {
        $scope.mapsApi = maps;
        $timeout(function(){
            $scope.calculateFare();
        }, 1000);
    });

    $scope.initModel();
});