package com.pcstar.people.activity;
/**
 * 描述：此类为程序运行第一个加载的Activity，
 * 其主要作用是：
 * 1.控制Activity的切换
 * 2.接收和处理报警数据
 * 
 */
import java.io.UnsupportedEncodingException;

import com.friendlyarm.AndroidSDK.HardwareControler;
import com.pcstar.people.socket.UDPClientSocket;
import com.pcstar.people.sqlite.Mysqlite;
import com.pcstar.people.utils.Configuration;
import com.pcstar.people.utils.Utils;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TabHost;
import android.widget.Toast;
public class MainActivity extends TabActivity implements OnCheckedChangeListener
{
	private String thread = "readThread";
	byte[] buf= new byte[300];
	public static TabHost mHost = null;
	private Button backButton;
	private Mysqlite mySqlite;
	
	private View view;
	private EditText ipEdit;//IP地址输入框
	private SharedPreferences sharedPreferences;//记录摄像机IP
	private String ipcameraIP;
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads()
		.detectDiskWrites()
		.detectNetwork() 
		.penaltyLog() 
		.build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		.detectLeakedSqlLiteObjects()
		.penaltyLog()
		.penaltyDeath()
		.build());

		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_maintabs);
		//建报警信息表
		setTable();		
		mHost = getTabHost();		
		view = getLayoutInflater().inflate(R.layout.alertdialog_style, null);
		ipEdit = (EditText)view.findViewById(R.id.alertdialog_edit); 
		ipEdit.setFocusableInTouchMode(false);
		ipEdit.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				ipEdit.setFocusableInTouchMode(true);
			}
		});
		backButton = (Button)findViewById(R.id.maintabs_backButton);
		backButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				Utils.showExitDialog(MainActivity.this);
			}
		});
		sharedPreferences = getSharedPreferences("data", MODE_WORLD_READABLE);
		ipcameraIP = sharedPreferences.getString("ip", "");
		ipEdit.setText(ipcameraIP);
		setIPDialog();
		//打开指定串口
		Configuration.fd = HardwareControler.openSerialPort(Configuration.DEV_NAME,Configuration.BAUD
				, Configuration.DATA_BITS, Configuration.STOP_BITS);//打开串口
		new readThread().start();//开启串口的监听线程		
        //获取绑定的手机号
        sharedPreferences = getSharedPreferences("data", MODE_WORLD_READABLE);
		Configuration.BIND_PHONE = sharedPreferences.getString("phone", "");		
	}
	/**
	 * 描述：初始化底部按钮
	 */
	private void initRadios() {
			mHost.addTab(buildTabSpec("a0", "a", new Intent(this,
					HomeVideoActivity.class)));
			mHost.addTab(buildTabSpec("b0", "b", new Intent(this,
					NewsFindActivity.class)));
			mHost.addTab(buildTabSpec("c0", "c", new Intent(this,
					TaskSetActivity.class)));
		((RadioButton) findViewById(R.id.radio_button0))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.radio_button1))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.radio_button4))
				.setOnCheckedChangeListener(this);
	}

	/**
	 * 描述：切换模块
	 */
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			switch (buttonView.getId()) {
			case R.id.radio_button0:
				mHost.setCurrentTabByTag("a0");
				break;
			case R.id.radio_button1:
				mHost.setCurrentTabByTag("b0");
				break;
			case R.id.radio_button4:
				mHost.setCurrentTabByTag("c0");
				break;
			}
		}
	}

	private TabHost.TabSpec buildTabSpec(String tag, String resLabel,
			Intent content) {
		return mHost
				.newTabSpec(tag)
				.setIndicator(resLabel,
						getResources().getDrawable(R.drawable.ic_launcher))
				.setContent(content);
	}
	
	@Override
	public void finish()
	{
		Utils.showExitDialog(MainActivity.this);
	}
	
    Handler handler = new Handler() {

        public void handleMessage(Message msg) {

            switch (msg.arg1) {

            case 0:
            	try {	
        		    Thread.sleep(90);
        		
        		   } catch(InterruptedException e) {
        		    e.printStackTrace();	
        		   }
                int len = HardwareControler.read(Configuration.fd, buf, buf.length);    
                String readStr = new String(buf, 0, len).replaceAll("\r","").trim();
                
                /**
                 * 报警信息
                 *  注意：需要先判断是否布防(人体红外探测器和门磁等防盗设备受布撤防控制，
                 * 		其余环境设备不受不撤防控制)
                 */
                //无线报警按钮
                //1.判断报警设备
                if (readStr.startsWith("AT+AA_C_315=04")) {
                	//2.通知报警器
                	write("AT+AA_RS485TX=01050013FF007DFF"+"\r");
//                	UDPClientSocket.send("AT+AA_RS485TX=01050013FF007DFF",Configuration.PC_HOST,Configuration.PC_PORT);
                	//3.发送短信通知
//                	Utils.sendSms(Configuration.BIND_PHONE, "无线报警按钮发送报警信息");
//                	Utils.sendSms("13051888641", "无线报警按钮发送报警信息");
                	//4.通知PAD
                	UDPClientSocket.send(readStr,Configuration.PAD_HOST,Configuration.PAD_PORT);
                	//5.通知PC
                	UDPClientSocket.send(readStr,Configuration.PC_HOST,Configuration.PC_PORT);
                	//6.存储报警信息
                	writeNewsToSql("无线报警按钮");
                	//7.弹出报警提示，并点击按钮关闭报警
                	setDialog("无线报警按钮","AT+AA_RS485TX=0105001300003C0F");
				}
                //有线报警按钮
                else if (readStr.startsWith("AT+AA_Z_RX_DT=Z2012,5,1")) {
                	write("AT+AA_RS485TX=01050013FF007DFF"+"\r");
//                	UDPClientSocket.send("AT+AA_RS485TX=01050013FF007DFF",Configuration.PC_HOST,Configuration.PC_PORT);
//                	Utils.sendSms(Configuration.BIND_PHONE, "有线报警按钮发送报警信息");
                	UDPClientSocket.send(readStr,Configuration.PAD_HOST,Configuration.PAD_PORT);
                	UDPClientSocket.send("AT+AA_Z_RX_DT=Z2012,5,1",Configuration.PC_HOST,Configuration.PC_PORT);
                	writeNewsToSql("有线报警按钮");
                	setDialog("有线报警按钮","AT+AA_RS485TX=0105001300003C0F");
				}
                //有线报警关闭信息
                else if (readStr.startsWith("AT+AA_Z_RX_DT=Z2012,5,0")) {
                	UDPClientSocket.send(readStr,Configuration.PAD_HOST,Configuration.PAD_PORT);
                	UDPClientSocket.send("AT+AA_Z_RX_DT=Z2012,5,0",Configuration.PC_HOST,Configuration.PC_PORT);
                	write("AT+AA_RS485TX=0105001300003C0F"+"\r");
//                	UDPClientSocket.send("AT+AA_RS485TX=0105001300003C0F",Configuration.PC_HOST,Configuration.PC_PORT);
				}
              //烟雾探测器报警信息
                else if (readStr.startsWith("AT+AA_Z_RX_DT=Z2010,5,1")) {
                	write("AT+AA_RS485TX=01050013FF007DFF"+"\r");
//                	UDPClientSocket.send("AT+AA_RS485TX=01050013FF007DFF",Configuration.PC_HOST,Configuration.PC_PORT);
//                	Utils.sendSms(Configuration.BIND_PHONE, "烟雾探测器发送报警信息");
                	writeNewsToSql("烟感探测器");
                	setDialog("烟感探测器","AT+AA_RS485TX=0105001300003C0F");
                	UDPClientSocket.send(readStr,Configuration.PAD_HOST,Configuration.PAD_PORT);
                	UDPClientSocket.send(readStr,Configuration.PC_HOST,Configuration.PC_PORT);
				}
                //烟雾探测器关闭报警信息
                else if (readStr.startsWith("AT+AA_Z_RX_DT=Z2010,5,0")) {
                	write("AT+AA_RS485TX=0105001300003C0F"+"\r"); 
//                	UDPClientSocket.send("AT+AA_RS485TX=0105001300003C0F",Configuration.PC_HOST,Configuration.PC_PORT);
                	UDPClientSocket.send(readStr,Configuration.PC_HOST,Configuration.PC_PORT);
				}
                if (Configuration.isDefend) {
                	//红外人体探测器报警信息
                    if (readStr.startsWith("AT+AA_C_315=00")) {
                    	
                    	write("AT+AA_RS485TX=01050013FF007DFF"+"\r");
//                    	UDPClientSocket.send("AT+AA_RS485TX=01050013FF007DFF",Configuration.PC_HOST,Configuration.PC_PORT);
//                    	Utils.sendSms(Configuration.BIND_PHONE, "红外人体探测器发送报警信息");
                    	setDialog("红外人体探测器","AT+AA_RS485TX=0105001300003C0F");
                    	writeNewsToSql("红外人体探测器");
                    	UDPClientSocket.send(readStr,Configuration.PAD_HOST,Configuration.PAD_PORT);
                    	UDPClientSocket.send(readStr,Configuration.PC_HOST,Configuration.PC_PORT);
    				}   
                    //门磁报警信息
                    else if (readStr.startsWith("AT+AA_Z_RX_DT=Z2013,5,1")) {
                    	write("AT+AA_RS485TX=01050013FF007DFF"+"\r");
//                    	UDPClientSocket.send("AT+AA_RS485TX=01050013FF007DFF",Configuration.PC_HOST,Configuration.PC_PORT);
                    	setDialog("门磁报警","AT+AA_RS485TX=0105001300003C0F");
                    	writeNewsToSql("门磁报警");
                    	UDPClientSocket.send("AT+AA_Z_RX_DT=Z2013,5,1",Configuration.PAD_HOST,Configuration.PAD_PORT);
                    	UDPClientSocket.send("AT+AA_Z_RX_DT=Z2013,5,1",Configuration.PC_HOST,Configuration.PC_PORT);
    				}                   
                    //关闭门磁报警信息
                    else if (readStr.startsWith("AT+AA_Z_RX_DT=Z2013,5,0")) {
                    	write("AT+AA_RS485TX=0105001300003C0F"+"\r");
//                    	UDPClientSocket.send("AT+AA_RS485TX=0105001300003C0F",Configuration.PC_HOST,Configuration.PC_PORT);
                    	UDPClientSocket.send("AT+AA_Z_RX_DT=Z2013,5,0",Configuration.PC_HOST,Configuration.PC_PORT);
    				}
                                       
				}
                //向PC和平板电脑发送指令
//                UDPClientSocket.send(readStr);
                Toast.makeText(MainActivity.this, readStr, Toast.LENGTH_SHORT).show();
                new readThread().start();//处理完消息后立即开启监听线程
                Log.d(thread,"接收到数据，新线程启动");
                break;
                
            case 1:
                HardwareControler.setLedState(1, 0);
                new readThread().start();
//                Log.d(thread,"没有数据，新线程启动");
                break;
            default:
            	
                break;
            }
        }
    };  
    /**
     * 描述：读取串口信息线程
     * @author Administrator
     *
     */
    class readThread extends Thread
    {        
        public void run()
        {
            Message msg = new Message();
            HardwareControler.setLedState(0, 0);
            if (Configuration.isRun == true) {
            	if (HardwareControler.select(Configuration.fd,2, 0)==1) {            
                    msg.arg1 = 0;     //received data.       
                }
                else {
                    msg.arg1 =1;
                    HardwareControler.setLedState(0, 1);
                }
                handler.sendMessage(msg);
			}
            
        }
    }
	/**
	 * 描述：向串口发指令
	 * @param str
	 */
	public void write(String str){
		try {
			HardwareControler.write(Configuration.fd, str.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    /**
     * 描述：报警提示对话框
     */
    public void setDialog(String news,final String order){
		final Builder builder = new AlertDialog.Builder(MainActivity.this);
		
		builder.setTitle("报警提示");
		builder.setMessage(news+"正在报警……");
		builder.setPositiveButton("关闭报警器", new AlertDialog.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				
				write(order+"\r");
//				UDPClientSocket.send(order,Configuration.PC_HOST,Configuration.PC_PORT);
			}
		});
		builder.create().show();
	}
    /**
     * 描述：向数据库写报警信息
     */
    public void writeNewsToSql(String strNews){
    	SQLiteDatabase db=mySqlite.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("time", Utils.getTime());
		values.put("news", strNews);
		db.insert("alerting_table", null, values);
		db.close();
    }
    /**
	 * 描述：建表的方法
	 */
    public  void setTable(){
    	mySqlite=new Mysqlite(MainActivity.this, "users.db", 1);
    	String sql ="create table if not exists alerting_table(time varchar(10) ,news varchar(10))";
		SQLiteDatabase db=mySqlite.getWritableDatabase();
		db.execSQL(sql);
		db.close();
    }

    /**
     * 描述：输入摄像头的网络IP
     */
    public void setIPDialog(){    	
    	new AlertDialog.Builder(MainActivity.this) 
		  .setTitle("请输入正确的摄像头网络IP") 
		  .setIcon(android.R.drawable.ic_dialog_info) 
		  .setView(view) 
		  .setPositiveButton("确定", new AlertDialog.OnClickListener() {			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				ipcameraIP = ipEdit.getText().toString().trim();
				Configuration.IPCAMERA_IP = ipcameraIP;
				initRadios();
				//保存IP
				Editor editor = sharedPreferences.edit();
				editor.putString("ip", ipcameraIP);
				editor.commit();
			}
		})
		  .setNegativeButton("取消", null) 
		  .show();
    }
}
