package com.activity.chaoran;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;

import org.kobjects.base64.Base64;

import com.chaoran.db.SqlHelpUtil;
import com.activity.chaoran.R;
import com.sys.SysData;
import com.util.DialogUtil;
import com.util.IoUtil;
import com.util.SysUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("NewApi")
public class NetWorkSet extends Activity {
	private EditText ip;
	private EditText port;
	private EditText itemName;
	private EditText bz;
	private SqlHelpUtil db;
	private SQLiteDatabase sDatabase;

	private Handler regHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.obj.equals("0")) {
				DialogUtil.builder(NetWorkSet.this, "提示信息", "注册成功！", 0);
			} else if (msg.obj.equals("1")) {
				DialogUtil.builder(NetWorkSet.this, "提示信息", "该PDA已注册！", 0);
			} else {
				DialogUtil.builder(NetWorkSet.this, "提示信息", "注册失败！" + msg.obj.toString(), 0);
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//
		BufferedReader br = null;
		BufferedWriter bw = null;
		File file = new File(getFilesDir().getAbsolutePath() + "/cr_pda_config");
		try {
	        if (!file.exists())  {
	        	file.createNewFile();
	        	//DialogUtil.builder(NetWorkSet.this, "错误信息", "文件不存在！", 0);
	        }
	        FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis);
			br = new BufferedReader(isr);
			String s = br.readLine();
			if (s == null || s.trim().length() < 1)
				throw new Exception("Update config data.");
			MainActivity.def_pbl = Float.parseFloat(s);
			if (MainActivity.def_pbl < 0.1 || MainActivity.def_pbl > 10.0)
				throw new Exception("请填写 0.1~10.0 之间的浮点数！");
		} catch (Exception e) {
			DialogUtil.builder(NetWorkSet.this, "错误信息", e.getMessage(), 0);
			MainActivity.def_pbl = 0.9f;
			try {
				FileOutputStream fos = new  FileOutputStream(file);
				OutputStreamWriter osw = new OutputStreamWriter(fos);
				bw = new BufferedWriter(osw);
				bw.append(Float.toString(MainActivity.def_pbl));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		//
		setContentView(R.layout.activity_net_work_set);
		ip = (EditText) findViewById(R.id.ip);
		port = (EditText) findViewById(R.id.port);
		itemName = (EditText) findViewById(R.id.itemName);
		bz = (EditText) findViewById(R.id.bz);
		TextView mactv = (TextView) findViewById(R.id.mac);
		mactv.setText("mac:" + SysUtil.getLocalMacAddress(NetWorkSet.this));
		TextView androidIDtv = (TextView) findViewById(R.id.androidID);
		androidIDtv.setText("sn:" + SysUtil.getSn());
		EditText te = (EditText) findViewById(R.id.itemName91);
		te.setText(Float.toString(MainActivity.def_pbl));
		// MainActivity.this.getResources().getDisplayMetrics().densityDpi
		TextView modeltv = (TextView) findViewById(R.id.model);
		modeltv.setText("型号:" + android.os.Build.MODEL.toLowerCase());
		//
		TextView phoneDpi = (TextView) findViewById(R.id.phoneDpi);
		phoneDpi.setText("密度:" + getResources().getDisplayMetrics().densityDpi);
		//
		db = new SqlHelpUtil(getApplicationContext());
		sDatabase = db.getWritableDatabase();
		System.out.println(sDatabase.getMaximumSize() + "--------------------------");
		String selectStr = "select col1,col2,col3 from systable where desc='network'";
		Cursor select_cursor = sDatabase.rawQuery(selectStr, null);
		if (select_cursor.moveToFirst()) {
			ip.setText(select_cursor.getString(0));
			port.setText(select_cursor.getString(1));
			itemName.setText(select_cursor.getString(2));
		}
		select_cursor.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_net_work_set, menu);
		return true;
	}

	public void onsub(View v) {
		EditText te = (EditText) findViewById(R.id.itemName91);
		try {
			MainActivity.def_pbl = Float.parseFloat(te.getText().toString());
		} catch (Exception ex) {
			DialogUtil.builder(NetWorkSet.this, "错误信息", "请填写 0.1~10.0 之间的浮点数！", 0);
			MainActivity.def_pbl = 0.9f;
		} finally {
			if (MainActivity.def_pbl < 0.1 || MainActivity.def_pbl > 10.0) {
				DialogUtil.builder(NetWorkSet.this, "错误信息", "请填写 0.1~10.0 之间的浮点数！", 0);
				MainActivity.def_pbl = 0.9f;
			}
		}
		//
		BufferedWriter bw = null;
		File file = new File(getFilesDir().getAbsolutePath() + "/cr_pda_config");

		try {
			FileOutputStream fos = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(fos);
			bw = new BufferedWriter(osw);
			bw.append(Float.toString(MainActivity.def_pbl));
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		//
		// DialogUtil.builder(NetWorkSet.this, "错误信息", "请检查网络！" +
		// MainActivity.def_pbl,0);
		if (ip.getText().toString().trim().equals("")) {
			DialogUtil.builder(NetWorkSet.this, "错误信息", "请填写IP！", 0);
			ip.requestFocus();
			return;
		}
		if (port.getText().toString().trim().equals("")) {
			DialogUtil.builder(NetWorkSet.this, "错误信息", "请填写端口！", 0);
			port.requestFocus();
			return;
		}
		if (itemName.getText().toString().trim().equals("")) {
			DialogUtil.builder(NetWorkSet.this, "错误信息", "请填写工程名！", 0);
			itemName.requestFocus();
			return;
		}
		String selectStr = "select col1 from systable where desc='network'";
		Cursor select_cursor = sDatabase.rawQuery(selectStr, null);
		String ipValue = ip.getText().toString().trim();
		String portValue = port.getText().toString().trim();
		String itemNameValue = itemName.getText().toString().trim();
		if (select_cursor.moveToFirst()) {
			sDatabase.execSQL("update systable   set col1='" + ipValue + "',col2='" + portValue + "',col3='" + itemNameValue + "' where desc='network'");
		} else {
			sDatabase.execSQL("insert into systable (col1,col2,col3,desc) values('" + ipValue + "','" + portValue + "','" + itemNameValue + "','network')");
		}
		select_cursor.close();
		SysData.url = "http://".concat(ipValue).concat(":").concat(portValue).concat("/").concat(itemNameValue);
		DialogUtil.builder(NetWorkSet.this, "提示", "设置成功！", 0);
	}

	public void onback(View v) {
		// Intent intent = this.getIntent();
		// setResult(0, intent);
		finish();

	}

	public void pdaRegister(View v) throws Exception {
		String mac = SysData.clientid;
		if (mac == null || mac.length() < 1) {
			DialogUtil.builder(NetWorkSet.this, "提示", "mac地址为空,请检查网络", 0);
			return;
		}
		HashMap map = new HashMap();
		map.put("mac", mac);
		map.put("bz", bz.getText().toString().trim());
		byte[] b = IoUtil.getbyte(map);
		String paramString = Base64.encode(b);
		new RunYmupThread(paramString, regHandler, "pdaRegister", 0).start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (db != null) {
			db.close();
			sDatabase.close();
		}
	}

}
