package lac.contextnet.sddl_longrunningtest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ipActivity extends Activity implements OnClickListener{
	
	TextView txtOldIp;

	TextView btnEnter;
	
	EditText ipAddress;
	
	Intent iMain;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.activity_login);
		
		txtOldIp = (TextView) findViewById(R.id.tagHelp);
		btnEnter = (TextView) findViewById(R.id.loginButton);
		ipAddress = (EditText) findViewById(R.id.ipAddress);

		btnEnter.setOnClickListener(this);
		
		//Verify for an IP address, if everything is OK show it
		if (hasIp()) {
			SharedPreferences config = getSharedPreferences(AppConfig.PREF_FILE, Context.MODE_PRIVATE);
			String ipAndPort = config.getString(AppConfig.IP_AND_PORT, "");
			txtOldIp.setText("IP: "+ipAndPort);
		}
		else {
			txtOldIp.setText("IP: Em Branco.");
		}
	}
	
	//check fo an IP
	private Boolean hasIp () {
		SharedPreferences config = getSharedPreferences(AppConfig.PREF_FILE, Context.MODE_PRIVATE);
		String ip = config.getString(AppConfig.IP_AND_PORT, "");
		if (AppConfig.isValidIpPort(ip))
			return true;
		return false;
	}

	@Override
	public void onClick(View v) {
		if(v == btnEnter) {
			String ipAndPort = ipAddress.getText().toString();
			boolean ipValid = AppConfig.isValidIpPort(ipAndPort);
			if(hasIp() || ipValid){
				// write ip and port to preferences
				if(ipValid)
					AppConfig.saveIpPort(getApplicationContext(), ipAndPort);
				// change activity
				iMain = new Intent(getApplication(), MainActivity.class);
				startActivity(iMain);
			}
			else if (!AppConfig.isValidIpPort(ipAndPort))
				txtOldIp.setText("IP: Inválido.");
			else
				txtOldIp.setText("IP: Em Branco.");
		}
	}
}
