package com.rob57530.smsserver;

import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity
{
	private Button m_btnStart;
	private Button m_btnStop;
	private EditText m_textHttp;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		m_btnStart = (Button) findViewById(R.id.btnStart);
		m_btnStop = (Button) findViewById(R.id.btnStop);
		m_textHttp = (EditText) findViewById(R.id.editTextHttp);
		m_btnStart.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startServer();
			}
		});
		m_btnStop.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				stopServer();
			}
		});

		final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
		m_textHttp.setText(p.getString("http", m_textHttp.getHint().toString()));

		updateButtons();
	}

	public void startServer()
	{
		String http = m_textHttp.getText().toString();

		SharedPreferences pr = PreferenceManager.getDefaultSharedPreferences(this);
		Editor edit = pr.edit();
		edit.putString("http", http);

		try
		{
			if (http.length() == 0)
				throw new Exception("Empty SMS Server");

            edit.putBoolean("running", true);

		}
		catch (Exception e)
		{
			Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
		}
        edit.commit();
        updateButtons();
	}

	public void stopServer()
	{
        SharedPreferences pr = PreferenceManager.getDefaultSharedPreferences(this);
        Editor edit = pr.edit();
        edit.putBoolean("running", false);
        edit.commit();
		updateButtons();
	}

	private boolean isServiceRunning()
	{
        SharedPreferences pr = PreferenceManager.getDefaultSharedPreferences(this);
        return pr.getBoolean("running", false);
	}

	private void updateButtons()
	{
		boolean is = isServiceRunning();
		m_btnStart.setEnabled(!is);
		m_btnStop.setEnabled(is);
		m_textHttp.setEnabled(!is);
	}
}
