app.directive('zlAddress', function () {
  return {
    restrict: 'E',
    scope: {
      item: '=',
      countries: '='
    },
    replace: false,
    templateUrl: 'directives/address/address.html',
    controller: function ($scope, $address, inform) {
      $scope.getAddressPT = function(zipcode) {
        $address.getAddressPT(zipcode, function (err, data) {
          if (err) {
            $scope.item.address = "";
            $scope.item.city = "";
            $scope.item.country = "";
            $scope.item.district = "";
            $scope.item.county = "";
            $scope.item.locality = "";
            return inform.add("Não foi possível completar o arruamento", { ttl: 2000, type: "warning" });
          }

          $scope.item.address = data.address;
          $scope.item.city = data.city;
          $scope.item.country = data.country;
          $scope.item.district = data.district;
          $scope.item.county = data.county;
          $scope.item.locality = data.locality;

          $address.getCoordinates(zipcode, function (err, coords) {
            if (!err) {
              $scope.item.coords = coords;
            }
          });
        });
      };

      $scope.validateZipcode = $address.validateZipcode;
    }
  };
});
