package com.mudassar.charityorganizer;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.snackbar.Snackbar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
public class Ambulance extends FragmentActivity implements OnMapReadyCallback,AmbulanceCallback,StatusCallback,CancelCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener,CompleteCallback,MapInterface {
private GoogleMap mMap;
double lat=0,lon=0;
Button request;
ImageView back,cancel;
int check=0;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private FusedLocationProviderApi locationProvider;
TextView status;
Marker m;
Toolbar toolbar;
int user_id=0;
private Handler handler;
private Runnable task = new Runnable() {
@Override
public void run() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork=null ;
if (cm!=null){
activeNetwork=cm.getActiveNetworkInfo();
}
if (activeNetwork!=null){
if (lat!=0&&lon!=0) {
StatusBackground statusBackground = new StatusBackground(Ambulance.this, Ambulance.this);
statusBackground.setMapInterface(Ambulance.this);
statusBackground.execute(user_id);
}
}
else {
final Snackbar s= Snackbar.make(findViewById(android.R.id.content),"Your Internet Connection is not Working",Snackbar.LENGTH_INDEFINITE);
s.setAction("Dismiss", new View.OnClickListener() {
@Override
public void onClick(View v) {
s.dismiss();
}
}).setActionTextColor(Color.GRAY).show();
}
handler.postDelayed(task,3000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ambulance);
locationProvider = LocationServices.FusedLocationApi;
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Please Turn On Your Location Services and Restart the Application", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("Dismiss", new View.OnClickListener() {
@Override
public void onClick(View v) {
snackbar.dismiss();
}
}).setActionTextColor(Color.GRAY);
View snackbarView = snackbar.getView();
locationRequest = new LocationRequest();
locationRequest.setInterval(30 * 1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(10);
if (locationRequest!=null &&googleApiClient!=null){
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient,
builder.build());
if (result != null) {
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
final LocationSettingsStates s = locationSettingsResult.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
Ambulance.this, 1000);
snackbar.show();
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
request=(Button)findViewById(R.id.amb);
back=(ImageView)findViewById(R.id.backq);
status=findViewById(R.id.ambstatus);
toolbar=(Toolbar)findViewById(R.id.toolbar5);
cancel=(ImageView)findViewById(R.id.cancel);
cancel.setVisibility(View.GONE);
SharedPreferences sharedPref = getSharedPreferences("LogIn", Context.MODE_PRIVATE);
user_id= sharedPref.getInt("id",0);
}
public void finis (View v){
finish();
}
public void cancel (View v){
CancelBackground cancelBackground=new CancelBackground(this,this);
cancelBackground.execute(user_id);
}
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
mMap.setMyLocationEnabled(true);
m = mMap.addMarker(new MarkerOptions().position(new LatLng(33.7294, 73.0931)).draggable(false));
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
m.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.marker1));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(false);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
LinearLayout info = new LinearLayout(Ambulance.this);
info.setOrientation(LinearLayout.VERTICAL);
TextView title = new TextView(Ambulance.this);
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER);
title.setTypeface(null, Typeface.BOLD);
title.setText(marker.getTitle());
TextView snippet = new TextView(Ambulance.this);
snippet.setTextColor(Color.GRAY);
snippet.setText(marker.getSnippet());
info.addView(title);
info.addView(snippet);
return info;
}
});
}
public void send(View v){
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork=null ;
if (cm!=null){
activeNetwork=cm.getActiveNetworkInfo();
}
if (activeNetwork!=null){
if (lat!=0&&lon!=0){
AmbulanceBackground ambulanceBackground=new AmbulanceBackground(this,this,user_id);
ambulanceBackground.execute(lat,lon);
}
else {
final Snackbar s= Snackbar.make(findViewById(android.R.id.content),"Turn on Your Location Services",Snackbar.LENGTH_INDEFINITE);
s.setAction("Dismiss", new View.OnClickListener() {
@Override
public void onClick(View v) {
s.dismiss();
}
}).setActionTextColor(Color.GRAY).show();
}
}
else {
final Snackbar s= Snackbar.make(findViewById(android.R.id.content),"Your Internet Connection is not Working",Snackbar.LENGTH_INDEFINITE);
s.setAction("Dismiss", new View.OnClickListener() {
@Override
public void onClick(View v) {
s.dismiss();
}
}).setActionTextColor(Color.GRAY).show();
}
}
@Override
public void checkRequestStatus(Integer status){
if (status==1){
Toast.makeText(this,"Request Submission Successful",Toast.LENGTH_LONG).show();
toolbar.setBackgroundColor(getResources().getColor(R.color.yellowgreen));
this.status.setText("Waiting");
request.setVisibility(View.GONE);
back.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
SearchBackground searchBackground=new SearchBackground(this,user_id);
searchBackground.execute(lat,lon);
}
else if (status==0){
Snackbar.make(findViewById(android.R.id.content),"Request Submission Unsuccessful",Snackbar.LENGTH_LONG).show();
}
}
@Override
public void checkStatus(String status){
if (status.equals("normal")){
reset();
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
this.status.setText("Ambulance Request");
request.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
}
else if (status.equals("waiting")){
toolbar.setBackgroundColor(getResources().getColor(R.color.yellowgreen));
this.status.setText("Waiting");
request.setVisibility(View.GONE);
back.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
}
else if (status.equals("accepted")){
toolbar.setBackgroundColor(getResources().getColor(R.color.green));
this.status.setText("Driver Found");
request.setVisibility(View.GONE);
back.setVisibility(View.GONE);
cancel.setVisibility(View.GONE);
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Received Help? If Yes Then Kindly Complete The Request.", Snackbar.LENGTH_INDEFINITE)
.setAction("Completed", new View.OnClickListener() {
@Override
public void onClick(View v){
CompleteBackground completeBackground=new CompleteBackground(Ambulance.this,Ambulance.this);
completeBackground.execute(user_id);
}
})
.setActionTextColor(Color.GRAY);
View snackbarView = snackbar.getView();
TextView textView = (TextView) snackbarView.findViewById(R.id.snackbar_text);
textView.setMaxLines(5);
snackbar.show();
}
else if (status.equals("fail")){
Snackbar.make(findViewById(android.R.id.content),"No Driver Found",Snackbar.LENGTH_LONG).show();
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
this.status.setText("Ambulance Request");
request.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
NormalBackground normalBackground=new NormalBackground(this);
normalBackground.execute(user_id);
}
}
@Override
protected void onStop(){
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
if (handler!=null){
handler.removeCallbacks(task);
}
}
@Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
@Override
protected void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
if (handler == null) {
handler = new Handler();
}
handler.removeCallbacks(task);
handler.post(task);
}
@Override
protected void onPause() {
super.onPause();
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
if (handler!=null){
handler.removeCallbacks(task);
}
}
@Override
public void cancelResult(int id) {
if (id==1){
Toast.makeText(this,"Request Cancellation Successful",Toast.LENGTH_LONG).show();
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
this.status.setText("Ambulance Request");
request.setVisibility(View.VISIBLE);
back.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
}
else if (id==0){
Snackbar.make(findViewById(android.R.id.content),"Request Cancellation Unsuccessful",Snackbar.LENGTH_LONG).show();
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location){
lat = location.getLatitude();
lon = location.getLongitude();
LatLng pos = new LatLng(lat, lon);
if (check == 0 && mMap != null) {
CameraUpdate camera = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 15);
mMap.moveCamera(camera);
m.setPosition(pos);
check++;
}
}
@Override
public void isCompleted(int status) {
if (status>0){
Snackbar.make(findViewById(android.R.id.content),"Request Completed",Snackbar.LENGTH_SHORT).show();
}
}
@Override
public void setMap(double lat, double lon, String name, String contact){
CameraUpdate camera = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 15);
mMap.moveCamera(camera);
Marker l = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).draggable(false));
l.setTitle("Driver Info");
l.setSnippet("Driver Name: "+name+"\n Driver Contact No: "+contact);
l.showInfoWindow();
}
public void reset() {
mMap.clear();
m = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).draggable(false));
m.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.marker1));
CameraUpdate camera = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 15);
mMap.moveCamera(camera);
}
}
class AmbulanceBackground extends AsyncTask<Double,Integer,Integer> {
Context c;
AmbulanceCallback ambulanceCallback;
ProgressDialog progressDialog;
int user_id;
public AmbulanceBackground(Context c,AmbulanceCallback ambulanceCallback,int user_id){
this.c=c;
this.ambulanceCallback=ambulanceCallback;
this.user_id=user_id;
}
@Override
protected Integer doInBackground(Double... params){
String url= c.getString(R.string.url)+"/Charity/submit_ambulance_request.php";
int r_status=0;
HttpRequest httpRequest= null;
try {
httpRequest = new HttpRequest(url);
HashMap<String ,String> value=new HashMap<>();
value.put("lat",Double.toString(params[0]));
value.put("c_id",Integer.toString(user_id));
value.put("lon",Double.toString(params[1]));
value.put("status","waiting");
JSONObject jsonObject=httpRequest.prepare(HttpRequest.Method.POST).withData(value).sendAndReadJSON();
r_status=jsonObject.getInt("r_status");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return r_status;
}
@Override
protected void onPreExecute(){
progressDialog=new ProgressDialog(c);
progressDialog.setMessage("Processing......");
progressDialog.show();
}
@Override
protected void onPostExecute(Integer s) {
progressDialog.dismiss();
ambulanceCallback.checkRequestStatus(s);
}
}
interface AmbulanceCallback {
public void checkRequestStatus (Integer status);
}
class SearchBackground extends AsyncTask<Double,Integer,Void>{
int user_id=0;
Context c;
public SearchBackground(Context c, int user_id){
this.user_id=user_id;
this.c=c;
}
@Override
protected Void doInBackground(Double... params){
String url= c.getString(R.string.url)+"searchDriver.php";
HttpRequest httpRequest= null;
try {
httpRequest = new HttpRequest(url);
HashMap<String ,String> value=new HashMap<>();
value.put("c_lat",Double.toString(params[0]));
value.put("c_id",Integer.toString(user_id));
value.put("c_lon",Double.toString(params[1]));
httpRequest.prepare(HttpRequest.Method.POST).withData(value).sendAndReadJSON();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
class StatusBackground extends AsyncTask<Integer,Integer,String> {
Context c;
StatusCallback statusCallback;
JSONObject jsonObject;
MapInterface mapInterface;
public StatusBackground(Context c,StatusCallback statusCallback){
this.c=c;
this.statusCallback=statusCallback;
}
public void setMapInterface(MapInterface mapInterface) {
this.mapInterface = mapInterface;
}
@Override
protected String doInBackground(Integer... params) {
String url= c.getString(R.string.url)+"check_ambulance_request_status.php";
String r_status="";
HttpRequest httpRequest= null;
try {
httpRequest = new HttpRequest(url);
HashMap<String ,String> value=new HashMap<>();
value.put("c_id",Integer.toString(params[0]));
jsonObject=httpRequest.prepare(HttpRequest.Method.POST).withData(value).sendAndReadJSON();
r_status=jsonObject.getString("r_status");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return r_status;
}
@Override
protected void onPreExecute(){
}
@Override
protected void onPostExecute(String s) {
if (jsonObject!=null){
if (s.equals("accepted")){
try {
mapInterface.setMap(jsonObject.getDouble("lat"),jsonObject.getDouble("lon"),jsonObject.getString("name"),jsonObject.getString("contact"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
statusCallback.checkStatus(s);
}
}
interface StatusCallback {
public void checkStatus (String status);
}
interface MapInterface{
public void setMap(double lat,double lon,String name,String contact);
}
class CancelBackground extends AsyncTask<Integer,Integer,Integer>{
Context c;
ProgressDialog progressDialog;
CancelCallback cancelCallback;
CancelBackground (Context c,CancelCallback cancelCallback){
this.c=c;
this.cancelCallback=cancelCallback;
}
@Override
protected Integer doInBackground(Integer... params) {
String url= c.getString(R.string.url)+"cancelAmbulanceRequest.php";
int r_status=0;
HttpRequest httpRequest= null;
try {
httpRequest = new HttpRequest(url);
HashMap<String ,String> value=new HashMap<>();
value.put("c_id",Integer.toString(params[0]));
JSONObject jsonObject= httpRequest.prepare(HttpRequest.Method.POST).withData(value).sendAndReadJSON();
r_status=jsonObject.getInt("r_status");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return r_status;
}
@Override
protected void onPreExecute() {
progressDialog=new ProgressDialog(c);
progressDialog.setMessage("Cancelling......");
progressDialog.show();
}
@Override
protected void onPostExecute(Integer integer) {
progressDialog.dismiss();
cancelCallback.cancelResult(integer);
}
}
interface CancelCallback {
public void cancelResult (int id);
}
class CompleteBackground extends AsyncTask<Integer,Integer,Integer>{
Context context;
CompleteCallback completeCallback;
JSONObject jsonObject;
CompleteBackground (Context context,CompleteCallback completeCallback){
this.context=context;
this.completeCallback=completeCallback;
}
@Override
protected Integer doInBackground(Integer... params){
int status = 0;
String url= context.getString(R.string.url)+"completeOrder.php";
HttpRequest httpRequest= null;
jsonObject=null;
try {
httpRequest = new HttpRequest(url);
HashMap<String ,String> value=new HashMap<>();
value.put("id",Integer.toString(params[0]));
jsonObject=httpRequest.prepare(HttpRequest.Method.POST).withData(value).sendAndReadJSON();
status=jsonObject.getInt("status");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
@Override
protected void onPostExecute(Integer status){
completeCallback.isCompleted(status);
}
}
interface CompleteCallback {
public void isCompleted (int status);
}
class NormalBackground extends AsyncTask<Integer,Integer,Integer>{
Context context;
JSONObject jsonObject;
NormalBackground (Context context){
this.context=context;
}
@Override
protected Integer doInBackground(Integer... params){
String url= context.getString(R.string.url)+"completeOrder.php";
HttpRequest httpRequest= null;
jsonObject=null;
try {
httpRequest = new HttpRequest(url);
HashMap<String ,String> value=new HashMap<>();
value.put("id",Integer.toString(params[0]));
jsonObject=httpRequest.prepare(HttpRequest.Method.POST).withData(value).sendAndReadJSON();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}