package jp.ito.camera;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Process;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {
	static final String XMPP_USER = "Xmpp.user";
	private static final String TAG = MainActivity.class.getSimpleName();
	private final int FP = ViewGroup.LayoutParams.FILL_PARENT;
	private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
	private	CameraView	_cameraView = null;
    private XmppView	_xmppView;			//XMPPビュー
    private SensorView	_sensorView;		//センサービュー
	private NoiseView	_noiseView;			//Noiseビュー
//	private boolean	_xmppMenuCalled = true;
//	private boolean	_sensorMenuCalled = true;
//	private boolean	_noiseMenuCalled = true;
//	private boolean	_mailMenuCalled = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate()");

        SharedPreferences pref = getSharedPreferences("jp.ito.mimamori",MODE_PRIVATE);
		String strAddress = pref.getString(XMPP_USER, "");
		if ( strAddress.length() == 0 ){
			Intent intent = new Intent(MainActivity.this, InitSetting.class);
			startActivityForResult(intent, INIT_SETTING);
		}

		LinearLayout layoutBig = new LinearLayout(this);
		layoutBig.setBackgroundColor(Color.LTGRAY);
		LinearLayout layoutTop = new LinearLayout(this);
		layoutBig.addView(layoutTop, new LinearLayout.LayoutParams(WC,WC));	//
		layoutBig.setOrientation(LinearLayout.VERTICAL);
		
		_cameraView = new CameraView(this,savedInstanceState);
		layoutTop.addView(_cameraView,new LinearLayout.LayoutParams(100,100));
		_sensorView = new SensorView(this);
		layoutTop.addView(_sensorView, new LinearLayout.LayoutParams(FP,90));	//
		_xmppView=new XmppView(this);
		layoutBig.addView(_xmppView, new LinearLayout.LayoutParams(FP,50));
		_noiseView=new NoiseView(this);
		_noiseView.setBackgroundColor(Color.LTGRAY);
		layoutBig.addView(_noiseView, new LinearLayout.LayoutParams(FP,FP));

		setContentView(layoutBig);

		// 設定値読み込み　￥-> onServiceConnectedに移動
//		senssorSetting();
//		mailSetting();
//		xmppSetting();
//		noiseSetting();
		
		// サービスを開始
		Intent intent = new Intent(this, MainService.class);
		startService(intent);
		IntentFilter filter = new IntentFilter(MainService.ACTION);
		registerReceiver(_receiver, filter);
		// サービスにバインド
		bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
   
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if(_mainService != null && _cameraView != null)
			_mainService.OnSaveState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if(_mainService != null && _cameraView != null)
			_mainService.OnLoadState(savedInstanceState);
	}

    @Override
    protected void onStart() {
        super.onStart();
		Log.d(TAG, "onStart()");
    }
    //アプリの開始
    @Override
    protected void onResume() {
        super.onResume();
		Log.d(TAG, "onResume()");
//        parameterChanged();
    }

    @Override
    protected void onPause(){
		super.onPause();
		Log.d(TAG, "onPause()");
//        _sensorView.stop();
//		_noiseView.recordPause(true);
	}

    //アプリの停止
    @Override
    protected void onStop() {
        super.onStop();
		Log.d(TAG, "onStop()");
    }    

    @Override
    protected void onDestroy(){
		Log.d(TAG, "onDestroy()");
		super.onDestroy();
//		_noiseView.recordStop();

		unbindService(serviceConnection); // バインド解除
		unregisterReceiver(_receiver); // 登録解除
		if (_mainService != null){
			_mainService.stopSelf(); // サービスは必要ないので終了させる。
		}
    }

    static final int MENU_XMPP	=	1;
    static final int MENU_MAIL	=	2;
    static final int MENU_NOISE	=	3;
    static final int MENU_SENSOR	=	4;
    static final int MENU_EXIT	=	9;
    static final int INIT_SETTING	=	99;
 // メニューボタンを最初にクリックした時に実行されるメソッド
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // メニューを生成します。
    	menu.add(Menu.NONE, MENU_XMPP, Menu.NONE, "XMPP設定");
        menu.add(Menu.NONE, MENU_MAIL, Menu.NONE, "メール設定");
//        menu.add(Menu.NONE, MENU_NOISE, Menu.NONE, "ノイズ設定");
        menu.add(Menu.NONE, MENU_SENSOR, Menu.NONE, "揺れ設定");
        menu.add(Menu.NONE, MENU_EXIT, Menu.NONE, "アプリ終了");
        return super.onCreateOptionsMenu(menu);
    }
    // メニューのアイテムが選択された時に実行されるメソッド
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 選択されたアイテムのタイトルをダイアログで表示します
        int id = item.getItemId();
        Intent intent = null;
        switch (id) {
        case MENU_XMPP:
            intent = new Intent(MainActivity.this, XmppSetting.class);
        	break;
        case MENU_MAIL:
            intent = new Intent(MainActivity.this, MailSetting.class);
        	break;
        case MENU_NOISE:
            intent = new Intent(MainActivity.this, NoiseSetting.class);
        	break;
        case MENU_SENSOR:
            intent = new Intent(MainActivity.this, SensorSetting.class);
        	break;
        case MENU_EXIT:
    		unbindService(serviceConnection); // バインド解除
    		unregisterReceiver(_receiver); // 登録解除
    		_mainService.stopSelf(); // サービスは必要ないので終了させる。
        	moveTaskToBack(true);
        	Process.killProcess(Process.myPid());
        	break;
        default:
        	break;
        }
        try {
        	startActivityForResult(intent, id);
        } catch (Exception ex) {
            Toast.makeText(MainActivity.this, "画面遷移に失敗しました。", Toast.LENGTH_LONG).show();
    		Log.d(TAG, "menu画面遷移に失敗しました。");
        }
        return true;
    }
    protected void onActivityResult(int id, int resultCode, Intent data) {
        switch (id) {
        case MENU_XMPP:
        	if (resultCode == RESULT_OK) {
        		xmppSetting();
        	}
        	break;
        case MENU_MAIL:
        	if (resultCode == RESULT_OK) {
        		mailSetting();
        	}
        	break;
        case MENU_NOISE:
        	if (resultCode == RESULT_OK) {
        		noiseSetting();
        	}
        	break;
        case MENU_SENSOR:
        	if (resultCode == RESULT_OK) {
        		senssorSetting();
        	}
        	break;
        case INIT_SETTING:
    		xmppSetting();
    		mailSetting();
    		noiseSetting();
    		senssorSetting();
        	break;
        default:
        	break;
        }
    }

//    public void parameterChanged(){
//    	if (_sensorMenuCalled) {
//    		senssorSetting();
//	    	_sensorMenuCalled = false;
//    	}
//    	if (_mailMenuCalled) {
//    		mailSetting();
//	    	_mailMenuCalled = false;
//    	}
//    	if (_xmppMenuCalled) {
//    		xmppSetting();
//    		_xmppMenuCalled = false;
//    	}
//    }
    private void senssorSetting(){
		if (_mainService != null){
	        SharedPreferences pref = getSharedPreferences("jp.ito.mimamori", MODE_PRIVATE);
			String strX = pref.getString(SensorSetting.LEVELX, "0");
			String strY = pref.getString(SensorSetting.LEVELY, "0");
			String strZ = pref.getString(SensorSetting.LEVELZ, "0");
			String str = pref.getString(SensorSetting.LEVEL, "1");
			boolean beep = pref.getBoolean(SensorSetting.BEEP, false);
	    	_mainService.sensorSetting(Integer.parseInt(strX), Integer.parseInt(strY), Integer.parseInt(strZ), Integer.parseInt(str), beep);
		}
    }
    private void noiseSetting(){
    	;
    }
    private void mailSetting(){
		if (_mainService != null){
	        SharedPreferences pref = getSharedPreferences("jp.ito.mimamori", MODE_PRIVATE);
	        String str = pref.getString(MailSetting.ADDRESS, "xxx@gmail.com");
	        String address = new String(str);
			str = pref.getString(MailSetting.PASSWORD, "password");
			String password = new String(str);
			str = pref.getString(MailSetting.HOST, "smtp.gmail.com");
			String host = new String(str);
			str = pref.getString(MailSetting.PORT, "587");
			String port = new String(str);
	    	_mainService.mailSetting(address, password, host, port);
		}
    }
    private void xmppSetting(){
		if (_mainService != null){
	        SharedPreferences pref = getSharedPreferences("jp.ito.mimamori", MODE_PRIVATE);
	    	String str = pref.getString(XmppSetting.USER, "xxx");
			String user = new String(str);
			str = pref.getString(XmppSetting.PASSWORD, "password");
			String password = new String(str);
			str = pref.getString(XmppSetting.HOST, "talk.google.com");
			String host = new String(str);
			str = pref.getString(XmppSetting.PORT, "5222");
			int port = Integer.parseInt(str);
			str = pref.getString(XmppSetting.SERVICE, "gmail.com");
			String service = new String(str);
			str = pref.getString(XmppSetting.PARENT, "xxx@gmail.com");
			String parent = new String(str);
    		_mainService.xmppInit(user, password, host, port, service, parent);
		}
    }

	private class CameraReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
//			Log.d(TAG, "onReceive() " + context + " " + intent);
			String action = intent.getStringExtra(MainService.BR_ACTION);
			if ( action == null ){
				Log.d(TAG, "onReceive() " + context + " " + intent);
				return;
			}
			if (action.equals(MainService.BR_TIMER)){
//				Toast toast = Toast.makeText(getApplicationContext(), "Time over!", Toast.LENGTH_LONG);
//				toast.show();
			} else if (action.equals(MainService.BR_XMPP)){
				String msg = intent.getStringExtra(MainService.BR_XMPP_MESSAGE);
				_xmppView._msg = msg;
				_xmppView.invalidate();
			} else if (action.equals(MainService.BR_NOISE)){
				int data = intent.getIntExtra(MainService.BR_NOISE_DATA, 0);
				_noiseView._data = data;
				_noiseView.invalidate();
			} else if (action.equals(MainService.BR_CAMERA)){
				_cameraView._camera = _mainService.getCamera();
			} else if (action.equals(MainService.BR_SENSOR)){
				_sensorView._x = intent.getIntExtra(MainService.BR_SENSOR_DATA_X, 0);
				_sensorView._y = intent.getIntExtra(MainService.BR_SENSOR_DATA_Y, 0);
				_sensorView._z = intent.getIntExtra(MainService.BR_SENSOR_DATA_Z, 0);
				_sensorView._diffX = intent.getIntExtra(MainService.BR_SENSOR_DATA_DIFF_X, 0);
				_sensorView._diffY = intent.getIntExtra(MainService.BR_SENSOR_DATA_DIFF_Y, 0);
				_sensorView._diffZ = intent.getIntExtra(MainService.BR_SENSOR_DATA_DIFF_Z, 0);
				_sensorView.invalidate();
			} else if (action.equals(MainService.BR_TOAST)){
				String str = intent.getStringExtra(MainService.BR_TOAST_MESSAGE);
				Toast toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG);
				toast.show();
			}
		}
	}
	
	private MainService _mainService;
	private final CameraReceiver _receiver = new CameraReceiver();
	
	private ServiceConnection serviceConnection = new ServiceConnection() {
//		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			_mainService = ((MainService.CameraBinder)service).getService();
//			_mainService.schedule(10000);
			xmppSetting();
			mailSetting();
			senssorSetting();
			noiseSetting();
			_cameraView._camera = _mainService.getCamera();
			_mainService.sensorInit((SensorManager)getSystemService(Context.SENSOR_SERVICE));
		}
//		@Override
		public void onServiceDisconnected(ComponentName className) {
			_mainService = null;
		}
	};
}