package net.indivia.hacklabbo.statusreader;

import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	public static boolean active = false;
	private static final String LOG_TAG = "MainActivity";
	private static SharedPreferences prefs;
	private Intent statusIntent;
	public final static int 
		MENU_SETTINGS_ID = 10,
		MENU_REFRESH_ID = 11;
	private static ImageButton ibStatusBtn;
	private static TextView 
		tvStatusValue,tvServerValue,tvLastRefreshValue,tvLastStatusValue;

	// Our handler for received Intents. This will be called whenever an Intent
	// with an action named "custom-event-name" is broadcasted.
	private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
		  @Override
		  public void onReceive(Context context, Intent intent) {
			  String message = intent.getStringExtra("msg");
			  Boolean isCicleService = intent.getBooleanExtra("isCicleService",false);
			  if(! message.equalsIgnoreCase(""))
			  	Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
			  	
			  setDisplay(null,null,null);
			  
			  Boolean refresh_service =prefs.getBoolean(getString(R.string.key_refresh_service), false);
			  Log.d(LOG_TAG,"refresh:"+refresh_service+" cicle:"+isCicleService);
			  if(isCicleService==false){
				  Log.d(LOG_TAG,"stop service");
				  stopService(statusIntent);
				  if (refresh_service){
					  Log.d(LOG_TAG,"restart service");
					  startService(setUpdateStatusIntent(statusIntent, true));
				  }
			  }
		  }
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		ibStatusBtn = (ImageButton) findViewById(R.id.status_btn);
		tvStatusValue = (TextView) findViewById(R.id.status_value);
		tvServerValue = (TextView) findViewById(R.id.server_value);
		tvLastRefreshValue = (TextView) findViewById(R.id.last_refresh_value);
		tvLastStatusValue = (TextView) findViewById(R.id.last_status_change_value);
		
		statusIntent = new Intent(this, StatusUpdate.class);
		LocalBroadcastManager.getInstance(this).registerReceiver(
				mMessageReceiver,
			    new IntentFilter("filter-updated"));
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		
		active = true;
		LoadPreferences();
	}
	
	private void LoadPreferences(){
		//le preferenze relative ai servizi
		Boolean refresh_service =prefs.getBoolean(getString(R.string.key_refresh_service), false);
	    Boolean update_service = prefs.getBoolean("update", false);
	    
	    //setto il display 
	    setDisplay(null,null,null);
		
	    //avvio il service che verifica se ci sono update del software
		if (update_service)
			startService(new Intent(this, CheckUpdate.class));
		
		
		//avvio il service che verifica se ci sono update dello stato
		if (refresh_service){
			stopService(statusIntent);
			startService(setUpdateStatusIntent(statusIntent,true));
		}
	}
	
	public Intent setUpdateStatusIntent(Intent intent, Boolean isCicleService){
		String serverName = prefs.getString(getString(R.string.key_server_name), StatusUpdate.DEF_SITE);
		int refresh_time =  Integer.parseInt(prefs.getString(getString(R.string.key_refresh_status_time), "600"));
		
		intent.putExtra("serverName", serverName);
		
		SharedPreferences states = getApplicationContext().getSharedPreferences(getString(R.string.key_states), 0);
		Boolean oldStatus = states.getBoolean(getString(R.string.key_status), false);
		intent.putExtra("oldStatus", oldStatus);
		intent.putExtra("isCicleService", isCicleService);
		if(isCicleService)
			intent.putExtra("refreshTime", refresh_time);
		
		return intent;
	}
	
	public void setDisplay(Boolean status, String last_refresh, String status_changed){
		String serverName = prefs.getString(getString(R.string.key_server_name), StatusUpdate.DEF_SITE);
	    SharedPreferences states = getApplicationContext().getSharedPreferences(getString(R.string.key_states), 0);
	    
	    String mai = getString(R.string.key_status_changed);
	    if(status == null)
	    	status = states.getBoolean(getString(R.string.key_status), false);
	    
	    if(last_refresh == null) 
	    	last_refresh =  states.getString(getString(R.string.key_last_refresh), mai);
	    
	    if(status_changed == null) 
	    	status_changed =  states.getString(getString(R.string.key_status_changed), mai);
	    
	    int statusImg = R.drawable.red_btn,
	    	statusValue = R.string.close;
	    if(status){
	    	statusImg = R.drawable.green_btn;
	    	statusValue = R.string.open;
	    }
	        
	    Log.d(LOG_TAG, "status_value: "+statusValue+" last_refresh: "+last_refresh+
	    		" status_changed: "+status_changed+" server_name: "+serverName);
	    
	    ibStatusBtn.setImageResource(statusImg);
    	tvStatusValue.setText(statusValue);
	    
	    tvLastRefreshValue.setText(last_refresh);
		tvLastStatusValue.setText(status_changed);
		tvServerValue.setText(serverName);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			startActivity(new Intent(this, PrefScreen.class));
		} else if( id== R.id.action_refresh){
			stopService(statusIntent);
			startService(setUpdateStatusIntent(statusIntent, false));
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onPause(){
		active=false;
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
	  // Unregister since the activity is about to be closed.
	  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
	  super.onDestroy();
	}
	
}