package com.example.psam;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.myview.DropEditText;
import com.example.tools.FileUtils;
import com.example.tools.StringUtils;
import com.example.tools.UIHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.rscja.deviceapi.PSAM;
import com.rscja.utility.StringUtility;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
	public final static String DEFAULT_SAVE_PATH = Environment
            .getExternalStorageDirectory()
            + File.separator
            + "handset"
            + File.separator;
    private PSAM mPSAM;

    @ViewInject(R.id.spVoltage)
    private Spinner spVoltage;
    @ViewInject(R.id.spBaud)
    private Spinner spBaud;

    @ViewInject(R.id.btnSet)
    private Button btnSet;
    @ViewInject(R.id.btnSend)
    private Button btnSend;
    @ViewInject(R.id.btnClear)
    private Button btnClear;
    @ViewInject(R.id.etCmd)
    private EditText etCmd;
    //    @ViewInject(R.id.etData)
    private DropEditText etData;
    @ViewInject(R.id.etParam)
    private EditText etParam;
    @ViewInject(R.id.tvPsamResult)
    private TextView tvPsamResult;
    @ViewInject(R.id.svResult)
    private ScrollView svResult;

    @ViewInject(R.id.cbSave)
    private CheckBox cbSave;
    @ViewInject(R.id.rbCard1)
    private RadioButton rbCard1;
    @ViewInject(R.id.rbCard2)
    private RadioButton rbCard2;

    String fileName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_psam);
        getActionBar().setDisplayHomeAsUpEnabled(false);

        ViewUtils.inject(this);

        mPSAM = PSAM.getInstance();

        cbSave.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    fileName = StringUtils.getTimeString() + ".txt";
                }
            }
        });
        etData = (DropEditText) findViewById(R.id.drop_edit);


        etData.setAdapter(new BaseAdapter() {
            private List<String> mList = new ArrayList<String>() {
                {
                    add("0084000004");
                    add("00A40000023F00");
                    add("00A40000020015");
                    add("00B0000000");
                    add("00C00000FF");
                }
            };

            @Override
            public int getCount() {
                return mList.size();
            }

            @Override
            public Object getItem(int position) {
                return mList.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView tv = new TextView(MainActivity.this);
                tv.setText(mList.get(position));
                return tv;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        new BaseInitTask(this) {

            @Override
            protected Boolean doInBackground(String... params) {


                boolean result = false;

                if (mPSAM != null) {
                    result = mPSAM.init();
                }

                return result;
            }

        }.execute();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mPSAM != null) {
            mPSAM.free();
        }
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;

            default:
                break;
        }

        return super.onMenuItemSelected(featureId, item);
    }


    @OnClick(R.id.btnSend)
    public void onClick_btnSend(View view) {

        String cmd = etCmd.getText().toString();
        String data = etData.getText().toString();

        if (!vailHexInput(cmd)) {
            UIHelper.ToastMessage(MainActivity.this,
                    R.string.rfid_mgs_error_nohex);
            etCmd.setFocusable(true);

            return;
        }

        if (data == null || data.length() == 0) {
            data = "0084000004";
        } else if (data.length() != 0 && !vailHexInput(data)) {
            UIHelper.ToastMessage(MainActivity.this,
                    R.string.rfid_mgs_error_nohex);
            etData.setFocusable(true);
            return;
        }


        String result = mPSAM.executeCmd(cmd, data);


        if (cbSave.isChecked()) {
            String content = "cmd:\n" + cmd + "\ndata:\n" + data
                    + "\nresult:\n" + result;

            saveRecords(content);

            UIHelper.ToastMessage(MainActivity.this,
                    R.string.psam_title_tips);
        }


        if (TextUtils.isEmpty(result)) {
//            appContext.playSound(2);
            result = getString(R.string.psam_msg_fail);
        } else {
//            appContext.playSound(1);
        }
        tvPsamResult.append(result + "\n");

        scrollToBottom(svResult, tvPsamResult);

    }

    @OnClick(R.id.btnClear)
    public void onClick_btnClear(View view) {
        tvPsamResult.setText("");
    }

    @OnClick(R.id.btnSet)
    public void onClick_btnSet(View view) {

        String card="01";

        if(rbCard1.isChecked())
        {
            card="01";
        }
        else
        {
            card="02";
        }

        mPSAM.executeCmd("02", card);

        int voltage = spVoltage.getSelectedItemPosition();

        String cmdVoltage = "00";

        switch (voltage) {
            case 0:
                cmdVoltage = "6E";
                break;
            case 1:
                cmdVoltage = "6D";
                break;
            case 2:
                cmdVoltage = "68";
                break;

            default:
                break;
        }

//        String param = etParam.getText().toString();
//        if (param.length() != 0 && !vailHexInput(param)) {
//            UIHelper.ToastMessage(PSAMActivity.this,
//                    R.string.rfid_mgs_error_nohex);
//            etData.setFocusable(true);
//            return;
//        }


        int baud = spBaud.getSelectedItemPosition();
        String param ="000"+baud;


        //02 01
        //02 02

        String result = mPSAM.executeCmd(cmdVoltage, param);


        if (cbSave.isChecked()) {
            String content = "cmd:\n" + cmdVoltage + "\ndata:\n" + param
                    + "\nresult:\n" + result;

            saveRecords(content);

            UIHelper.ToastMessage(MainActivity.this,
                    R.string.psam_title_tips);
        }


        if (TextUtils.isEmpty(result)) {
//            appContext.playSound(2);
            result = getString(R.string.psam_msg_fail);
        } else {
//            appContext.playSound(1);
        }
        tvPsamResult.append(result + "\n");
        scrollToBottom(svResult, tvPsamResult);
    }


    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.menu_psam, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getItemId() == R.menu.menu_psam) {
			String verStr = "";
			if(mPSAM != null) {
				verStr = mPSAM.executeCmd("ff", "");
			}
			char[] verArr = StringUtils.HexStringToChars(verStr);
			UIHelper.alert(this, R.string.action_psam_ver, String.valueOf(verArr), R.drawable.webtext);
		}
		return super.onOptionsItemSelected(item);
	}

    /**
     * 保存数据
     *
     * @param data
     */
    public void saveRecords(String data) {


        if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(data)) {
            return;
        }

        if (!FileUtils.checkSaveLocationExists()) {
            return;
        }

        String path = DEFAULT_SAVE_PATH + "/PSAM/";

        if (!FileUtils.checkFilePathExists(path)) {
            FileUtils.createPath(path);
        }

        File logFile = new File(path + fileName);

        FileWriter fw = null;

        try {

            boolean isNew = false;

            if (!logFile.exists()) {

                logFile.createNewFile();
                isNew = true;
            }

            fw = new FileWriter(logFile, true);
            if (isNew) {
//                fw.append("\n******" + appContext.getSerialNum() + "******\n");
            	fw.append("\n******" + android.os.Build.SERIAL + "******\n");
            }


            String card="01";

            if(rbCard1.isChecked())
            {
                card="01";
            }
            else
            {
                card="02";
            }

            data="card:\n"+card+"\n"+data;

            fw.append(data + " \n"
                    + StringUtils.getTimeFormat(System.currentTimeMillis())
                    + "\n-- \n\n");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                }
            }
        }

    }

    /**
     * 验证十六进制输入是否正确
     *
     * @param str
     * @return
     */
    public boolean vailHexInput(String str) {

        if (str == null || str.length() == 0) {
            return false;
        }

        // 长度必须是偶数
        if (str.length() % 2 == 0) {
            return StringUtility.isHexNumberRex(str);
        }

        return false;
    }
    
    /**
	 * 将ScrollView根据内部控件高度定位到底端
	 * 
	 * @param scroll
	 * @param inner
	 */
	public void scrollToBottom(final View scroll, final View inner) {

		Handler mHandler = new Handler();

		mHandler.post(new Runnable() {
			public void run() {
				if (scroll == null || inner == null) {
					return;
				}
				int offset = inner.getMeasuredHeight() - scroll.getHeight();
				if (offset < 0) {
					offset = 0;
				}

				scroll.scrollTo(0, offset);
			}
		});
	}
}
