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

myApp.controller('myAppCtrl', ['$scope', function($scope, $window){
    $scope.expenseRecords = [];
    $scope.mHomePage = 'frontScreen.html';
    $scope.mIncludeFile = $scope.mHomePage;
    $scope.mWheninMainPage = true;
    $scope.l = null;
    //
    //New Record Variables
    this.mAmount = null;
    this.mExpDescription = null;
    this.mLocation = "A";
    this.mLocationDesc = null;
    this.mDate = null;
    $scope.mLng = null;
    $scope.mLat = null;
    //
    this.message = null;
    
    this.locationTracking = function(){
        //alert("Tracking started");
        //Location tracking
        var geocoder;
        var tmpLocation;
        geocoder = new google.maps.Geocoder();
            //
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
        } 
        
        //Get the latitude and the longitude;
        function successFunction(position) {
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            codeLatLng(lat, lng)
        }

        function errorFunction(){
            //alert("Geocoder failed");
        }

        function codeLatLng(lat, lng) {
            var tmpLocation;
            $scope.mLng = lng;
            $scope.mLat = lat;
            var latlng = new google.maps.LatLng(lat, lng);
                geocoder.geocode({'latLng': latlng}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                     //formatted address
                    //find country name
                        for (var i=0; i<results[0].address_components.length; i++) {
                            for (var b=0;b<results[0].address_components[i].types.length;b++) {

                            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                                    //this is the object you are looking for
                                    city= results[0].address_components[i];
                                    break;
                                }
                            }
                        }
                        this.mLocation =  results[0].formatted_address;
                        tmpLocation =  results[0].formatted_address;
                        $scope.l =  results[0].formatted_address;
                        $scope.$apply();
                    //city data
                    } else {
                      //alert("No results found");
                    }
                  } else {
                    //alert("Geocoder failed due to: " + status);
                  }
                });
              }
    }
    
    $scope.openDatabase = function(){
        $scope.expenseRecords = [];
        var db = openDatabase('expmgr', '1.0', 'Expenser Manager', 2 * 1024 * 1024);
        db.transaction(function (tx) {
            tx.executeSql("CREATE TABLE IF NOT EXISTS expense ( " +
            "e_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "e_trans_desc VARCHAR(50), " +
            "e_location VARCHAR(50), " +
            "e_location_desc VARCHAR(50), " +
            "e_trans_date VARCHAR(10), " +
            "e_trans_amt VARCHAR(7), " + 
            "e_category VARCHAR(20), " + 
            "e_lng VARCHAR(15), " + 
            "e_lat VARCHAR(15))" , null, function(){console.log("insert ok")}, function(tx, error){console.log("ERR CREATE:" + error)})
        });   
        
       // db.transaction(function(tx){
        //   var sqlString = "INSERT INTO expense (e_trans_desc, e_location, e_location_desc)" + 
          //      "VALUES ('Grosaries', 'Foresthill', 'Safeway')";
            //tx.executeSql(sqlString, null, function(){console.log('GOOD')},function(tx, error){console.log("ERR:" + error)});
        //});
        
        var expenseSelect = "select * from expense";
        var itm = null;
        var amt = null
        db.transaction(function(tx){
        tx.executeSql(expenseSelect, [], function(tx, results) {
            var len = results.rows.length,
                i = 0;
            for (i=0; i < len; i = i + 1) {
                //console.log(results.rows.item(i));
                itm =  results.rows.item(i);
                amt = itm.e_trans_amt;
                amt = accounting.formatMoney(amt, "$", 2, ",", ".");
                $scope.expenseRecords.push({e_id: itm.e_id, e_trans_desc: itm.e_trans_desc, e_location:itm.e_location, e_location_desc: itm.e_location_desc, e_trans_date: itm.e_trans_date, e_trans_amt: amt, e_category: itm.e_category, e_lng: itm.e_lng, e_lat: itm.e_lat});
                $scope.$apply();
            }
            //callback(employees);
        //$scope.$scope.expenseRecords = x;    
        console.log($scope.expenseRecords);
        });
        });
        console.log($scope.expenseRecords);
        //$scope.$scope.expenseRecords = [];;
        
    }
    
    //$scope.openDatabase();
    this.fPreparetoCreateRecord = function(){
        this.locationTracking();
        $scope.mWheninMainPage = false; 
        $scope.mIncludeFile = 'addNewExpense.html';
    }

    $scope.fBackHome =function(){
        $scope.mIncludeFile = $scope.mHomePage;
        $scope.mWheninMainPage = true; 
        console.log("BACK TO HOME");
        console.log($scope.mIncludeFile);
    }
    
    this.fSaveRecord = function(pL){
        this.mLocation = pL;
        if(this.mExpDescription == '' || this.mExpDescription == null){
            this.message = "Please Enter Trans. Description";
            $("#infor-banner-addnew").show();
            $("#infor-banner-addnew").fadeOut(2000);
            return;   
        }
        //
        if(this.mAmount == '' || this.mAmount == null || this.mAmount == 0){
            this.message = "Please Enter Amount";
            $("#infor-banner-addnew").show();
            $("#infor-banner-addnew").fadeOut(2000);
            return;   
        }
        
        var db = openDatabase('expmgr', '1.0', 'Expenser Manager', 2 * 1024 * 1024);
           var sqlString = "INSERT INTO expense (e_trans_desc, e_location, e_location_desc, e_trans_date, e_trans_amt, e_lng, e_lat) " + 
               "VALUES ('" + this.mExpDescription + "', '" +
                this.mLocation + "', '" +
                this.mLocationDesc + "', '" +
                this.mDate + "', '" +
                this.mAmount + "', '" +
                $scope.mLng + "', '" + 
                $scope.mLat + "')";
        db.transaction(function(tx){
            tx.executeSql(sqlString, null, function(){console.log('GOOD')},function(tx, error){console.log("ERR:" + error)});
        });
        $scope.openDatabase();    
        $scope.fBackHome();
        $scope.mIncludeFile = $scope.mHomePage;
        $scope.mWheninMainPage = true; 
        this.message = "Expense Saved..!"
        $("#infor-banner").show();
        $("#infor-banner").fadeOut(2000);
        
        this.mAmount = null;
        this.mExpDescription = null;
        this.mLocation = null;
        this.mLocationDesc = null;
        this.mDate = null;
    }
    
    $scope.fReadBarcode = function(){
       $scope.mBarcodeVal = getBarcodeFromImage('barcode');
    }
    
   this.droptable = function(pButtonIndex){
       if(pButtonIndex == 1){
            var db = openDatabase('expmgr', '1.0', 'Expenser Manager', 2 * 1024 * 1024);
            db.transaction(function(tx){
            tx.executeSql("DROP TABLE expense",[], 
                function(tx,results){console.log("Successfully Dropped")},
                function(tx,error){console.log("Could not delete")}
                );
            });
       }
    }
    
    this.dropTableConfirmation = function(){
        navigator.notification.confirm(
            'You are the winner!',  // message
            this.droptable,                // callback to invoke with index of button pressed
            'Game Over',            // title
            'Restart,Exit'          // buttonLabels
        );    }
    
    
}]);
