package com.example.service_gps01;


import android.Manifest;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{

    private Button btn_start, btn_stop, btn_service;
    private TextView textView;
    private BroadcastReceiver broadcastReceiver;
    
    private LocationManager query_location   = null;
    
	String service_name = "com.example.service_gps01.GPS_Service";
	

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_start = (Button) findViewById(R.id.button);
        btn_stop = (Button) findViewById(R.id.button2);
        btn_service = (Button) findViewById(R.id.button1);
        
        textView = (TextView) findViewById(R.id.textView);

        //if(!runtime_permissions())
        enable_buttons();

    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        if(broadcastReceiver == null)
        {
	            broadcastReceiver = new BroadcastReceiver()
	            {
		                @Override
		                public void onReceive(Context context, Intent intent)
		                {
			                    //textView.append("\n" +intent.getExtras().get("coordinates"));
			                	// OK
			                    Object titi = intent.getExtras().get("coordinates");
			                    String toto = titi.toString();
			                    textView.setText(toto);
			                    
			                    // OK
			                    String lili = (String) intent.getExtras().get("coordinates");
			                    textView.setText(lili);
			                    Toast.makeText(getBaseContext(), "Refresh datas ...", Toast.LENGTH_SHORT).show();
			                    
			                    /*
			                    try {
									Thread.sleep(5000);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}*/
			                    
			                    Handler handler = new Handler();
			                    handler.postDelayed(new Runnable() 
			                    {
			                        public void run() {
			                            textView.setText("");
			                         // Actions to do after 5 seconds
			                        }
			                    }, 5000);
		
		                }
	            };
        }
        
        registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
    }

    @Override
    protected void onDestroy() 
    {
	        super.onDestroy();
	        
	        if(broadcastReceiver != null)
	        {
	            unregisterReceiver(broadcastReceiver);
	        }
	        
	        if(GPS_Service.locationManager != null)
	        {
	            //noinspection MissingPermission
	        	//GPS_Service.locationManager.removeUpdates((LocationListener) this);
	        	 Intent i = new Intent(getApplicationContext(),GPS_Service.class);
	             stopService(i);
	             Toast.makeText(getBaseContext(), "Forced quit ...", Toast.LENGTH_SHORT).show();   
	        	
	        }
    }

   

    private void enable_buttons() 
    {

	        btn_start.setOnClickListener(new View.OnClickListener()
	        {
	            @Override
	            public void onClick(View view) 
	            {
	                Intent i =new Intent(getApplicationContext(),GPS_Service.class);
	                startService(i);
	                Toast.makeText(getBaseContext(), "Service running ...", Toast.LENGTH_SHORT).show();
	                
	            }
	        });
	
	        btn_stop.setOnClickListener(new View.OnClickListener()
	        {
	            @Override
	            public void onClick(View view)
	            {
	                Intent i = new Intent(getApplicationContext(),GPS_Service.class);
	                stopService(i);
	                Toast.makeText(getBaseContext(), "Service stopped", Toast.LENGTH_SHORT).show();
	            }
	        });

	        
	        btn_service.setOnClickListener( new OnClickListener()
			 {
			 
				 @Override
				 public void onClick(View actuelView)
				 {
					 boolean test = isServiceRunning();  
					 if(test == true)
					 {
						 Toast.makeText(getApplicationContext(), "youpi", Toast.LENGTH_LONG).show(); 
					 }
					 else
					 {
						 Toast.makeText(getApplicationContext(), "No service !", Toast.LENGTH_LONG).show(); 
					 }
				 }
				 
			 });
	        
	        
	        
	    	
	        
    }

    private boolean isServiceRunning() 
	{
		
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
		{
//			if("com.example.service_app01.class_service".equals(service.service.getClassName())) 
			if(service_name.equals(service.service.getClassName())) 
			{
				return true;
			}
		}
	        return false;
	}

    
 /*   
    private boolean runtime_permissions() {
        if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){

            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);

            return true;
        }
        return false;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100){
            if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
                enable_buttons();
            }else {
                runtime_permissions();
            }
        }
    }
    */
}
