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.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 {
	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()");
		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); // 登録解除
		_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;
 // メニューボタンを最初にクリックした時に実行されるメソッド
    @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, "揺れ設定");
        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);
//            _xmppMenuCalled = true;
        	break;
        case MENU_MAIL:
            intent = new Intent(MainActivity.this, MailSetting.class);
//            _mailMenuCalled = true;
        	break;
        case MENU_NOISE:
            intent = new Intent(MainActivity.this, NoiseSetting.class);
//            _noiseMenuCalled = true;
        	break;
        case MENU_SENSOR:
            intent = new Intent(MainActivity.this, SensorSetting.class);
//            _sensorMenuCalled = true;
        	break;
        default:
        	break;
        }
        try {
//            startActivity(intent);
        	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;
        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, "6");
			String strY = pref.getString(SensorSetting.LEVELY, "6");
			String strZ = pref.getString(SensorSetting.LEVELZ, "6");
			boolean beep = pref.getBoolean(SensorSetting.BEEP, false);
	    	_mainService.sensorSetting(Integer.parseInt(strX), Integer.parseInt(strY), Integer.parseInt(strZ), beep);
		}
    }
    private void noiseSetting(){
    	;
    }
    private void mailSetting(){
		if (_mainService != null){
	        SharedPreferences pref = getSharedPreferences("jp.ito.mimamori", MODE_PRIVATE);
	        String str = pref.getString(MailSetting.ADDRESS, "boo@foo.uu");
	        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, "boo");
			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);
    		_mainService.xmppInit(user, password, host, port, service);
		}
    }

	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)){
				int x = intent.getIntExtra(MainService.BR_SENSOR_DATA_X, 0);
				int y = intent.getIntExtra(MainService.BR_SENSOR_DATA_Y, 0);
				int z = intent.getIntExtra(MainService.BR_SENSOR_DATA_Z, 0);
				_sensorView._x = x;
				_sensorView._y = y;
				_sensorView._z = z;
				_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;
		}
	};
}