package com.example.scantest;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.tool.Scan;
import com.tool.UsbScanDevice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class HomeActivity extends Activity {
    TextView status;
    TextView mymsg;
    TextView version;
    Button start;
    Button stop;
    private ListView myListView;

    private Scan Tsexample;
    private List<ScanDevice> namesList;
    private int selectPosition = -1;
    ScanDevice selectScanDevice;
    
    static int uiDecodeCnt = 0;

    public static final String TAG = "SCANDEMO";
    
    public MyAdapter myAdapter;
    
    public boolean ExitFlag = false;
    public boolean RetryScan = false;
    public boolean BusyFlag = false;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        status = (TextView) findViewById(R.id.device_status);
        mymsg = (TextView) findViewById(R.id.device_msg);
        version = (TextView) findViewById(R.id.device_version);
        start = (Button) findViewById(R.id.start_scan);
        stop = (Button) findViewById(R.id.stop_scan);
        myListView = (ListView) findViewById(R.id.device_list);
        Tsexample = new Scan(this, myHandler);
        Scan.TsDataCallBack tsdatacallback = new Scan.TsDataCallBack() {
            @Override
            public int ts_get_data_fun(int iNode, byte[] pParam, byte[] pbuf, int uiBufLen) {
                byte[] decode = new byte[uiBufLen];   //数据域
                System.arraycopy(pbuf, 0, decode, 0, uiBufLen);

                ScanMsg(Scan.HANDLER_SCAN_DEC, iNode, 0, new String(decode));

                System.out.printf("[%03d]len:%d, buf:",++uiDecodeCnt, uiBufLen);
//                for (byte b : decode) {
//                    System.out.printf("%c", b);
//                }
//                System.out.println();
                return 0;
            }
        };

        Scan.TsStateCallBack tsstatecallback = new Scan.TsStateCallBack() {
            @Override
            public int ts_scan_state_fun(int iNode, byte[] pParam,byte ucState) {
                String stbuf;
                byte[] ucBufTemp;
                byte[] ucBufTemp1;
                int iRet;
                System.out.printf("状态=%d\r\n",ucState);

                if(ucState == 1)
                {
                    ScanMsg(Scan.HANDLER_SCAN_TEXT, 0, 0, "设备连接成功");
                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_product_name(iNode,ucBufTemp, ucBufTemp.length);

                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, product name:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, product name:%s\r\n",iRet,"null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_product_id(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, product id:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, product id:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_product_date(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, product date:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, product date:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_custom_name(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, custom name:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, custom name:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_custom_id(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, custom id:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, custom id:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_custom_date(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, custom date:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, custom date:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_firmware_version(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, firmware version:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, firmware version:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_hardware_version(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, hardware version:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, hardware version:%s\r\n", iRet, "null");
                    }

                    ucBufTemp = new byte[128];
                    iRet = Tsexample.ts_scan_get_complex_sn(iNode,ucBufTemp, ucBufTemp.length);
                    if(iRet > 0)
                    {
                        ucBufTemp1 = new byte[iRet];
                        System.arraycopy(ucBufTemp, 0, ucBufTemp1, 0, iRet);
                        stbuf = new String(ucBufTemp1);
                        System.out.printf("Len:%d, COMPLEX SN:%s\r\n", iRet, stbuf);
                    }
                    else
                    {
                        System.out.printf("Len:%d, COMPLEX SN:%s\r\n", iRet, "null");
                    }
                }
                else
                {
                    ScanMsg(Scan.HANDLER_SCAN_TEXT, 0, 0, "设备断开连接");
                }
                return 0;
            }
        };

        Tsexample.ts_scan_get_data_fun_register(null, tsdatacallback);
        Tsexample.ts_scan_state_fun_register(null, tsstatecallback);

        ScanMsg(Scan.HANDLER_SCAN_VERSION_TEXT,0,0,"版本:V"+Tsexample.ts_scan_get_version()+" 模块类别:" + Tsexample.ts_scan_get_product_type());
        Tsexample.ts_scan_init();

        namesList = new ArrayList<ScanDevice>();
        myAdapter = new MyAdapter(this,namesList);
        myListView.setAdapter(myAdapter);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取选中的参数
                selectPosition = position;
                myAdapter.notifyDataSetChanged();
                selectScanDevice = namesList.get(position);
                Log.w(TAG, "Select:" + namesList.get(position).getBandname());
            }
        });
        
        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new StartDecodeRunnable()).start();
            }
        });
        
        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new StopDecodeRunnable()).start();
            }
        });
        
    }
    
    private void AddDevice(int node)
    {
        myAdapter.addListItem(node);
        myAdapter.notifyDataSetChanged();
    }

    private void ClearDeviceList()
    {
        myAdapter.clearList();
        myAdapter.notifyDataSetChanged();
    }
    
    private void ChangeDeviceStatus(int node, int status)
    {
        myAdapter.ChangeItemStatus(node, status);
        myAdapter.notifyDataSetChanged();
    }
    
    private void Sleep(long ms)
    {
        try {Thread.sleep(ms);} catch (InterruptedException e) {e.printStackTrace();}
    }
    
    private class StartDecodeRunnable implements Runnable{
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Log.w(TAG, "StartDecodeRunnable");

            while(BusyFlag){Sleep(10);};
            BusyFlag = true;
            if(selectPosition < 0)
            {
                BusyFlag = false;
                return;
            }
            ScanDevice curDevice = namesList.get(selectPosition);
            //myScan.SetOneScanTime(curDevice.GetNode(),50,0); /**设置单次扫码时间**/

            try {
                Tsexample.ts_scan_decode_start(curDevice.GetNode());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            BusyFlag = false;
        }
    }
    
    private class StopDecodeRunnable implements Runnable{
        @Override
        public void run() {
            while(BusyFlag){Sleep(10);};
            BusyFlag = true;
            if(selectPosition < 0)
            {
                BusyFlag = false;
                return;
            }
            ScanDevice curDevice = namesList.get(selectPosition);
            try {
                Tsexample.ts_scan_decode_stop(curDevice.GetNode());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            BusyFlag = false;
        }
    }

    private void ScanMsg(int mode, int type, int status, Object value)
    {
        Message msg = new Message();
        msg.what = mode;
        msg.arg1 = type;
        msg.arg2 = status;
        msg.obj = value;
        myHandler.sendMessage(msg);
    }
    
    Handler myHandler = new Handler()
    {
        public void handleMessage(Message msg)  
        {  
            int deviceId;
            deviceId = msg.arg1;
            switch(msg.what)  
            {
                case Scan.HANDLER_SCAN_STATUS:
                    AddDevice(deviceId);
                    ChangeDeviceStatus(deviceId, ScanDevice.DEVICE_CONNECT);
                    break;
                case Scan.HANDLER_SCAN_DEC:
                    RetryScan= true;
                    Log.w(TAG, "HANDLER_SCAN_DEC");
                    
    				Log.w(TAG, "1D RawData1: " + (String)msg.obj);					
					String aa = (String)msg.obj;
					Log.w(TAG, "1D RawData2: " + aa + " DataLen: " + aa.length());
					
                    mymsg.setText("[" + (uiDecodeCnt) + "]" + "[设备号:" + deviceId + "]" + "解码数据：" + (String)msg.obj);
                    break;

                case Scan.HANDLER_SCAN_TEXT:
//                    status.append((String)msg.obj);
                    status.setText((String)msg.obj);
                    break;
                case Scan.HANDLER_SCAN_CLEAR:
                    selectPosition = -1;
                    ClearDeviceList();
                    ChangeDeviceStatus(deviceId, ScanDevice.DEVICE_CONNECT);
                    break;
                case Scan.HANDLER_SCAN_VERSION_TEXT:
                    version.setText((String)msg.obj);
                    break;
            }
        }
    };
    
    public class MyAdapter extends BaseAdapter{
        Context context;
        List<ScanDevice> brandsList;
        LayoutInflater mInflater;
        public MyAdapter(Context context,List<ScanDevice> mList){
            this.context = context;
            this.brandsList = mList;
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return brandsList.size();
        }
        
        public void clearList(){
            brandsList.clear();
        }
        
        public void ChangeItemStatus(int node, int status) {
            
            ScanDevice curDevice;
            int count = brandsList.size();
            for(int i = 0; i < count; i ++)
            {
                curDevice = brandsList.get(i);
                if(curDevice.GetNode() == node)
                {
                    curDevice.setStatus(status);
                    brandsList.set(i, curDevice);
                    break;
                }
            }
        }
        
        public void addListItem(int node){
            
            Log.w(TAG, "add " + "Device" + node);
            ScanDevice myDevice = new ScanDevice(node);
            brandsList.add(myDevice);
        }

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

        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            if(convertView == null){
                convertView = mInflater.inflate(R.layout.adapter_item,parent,false);
                viewHolder = new ViewHolder();
                viewHolder.name = (TextView)convertView.findViewById(R.id.id_name);
                viewHolder.status = (TextView)convertView.findViewById(R.id.id_staus);
                viewHolder.select = (RadioButton)convertView.findViewById(R.id.id_select);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder)convertView.getTag();
            }
            viewHolder.name.setText(brandsList.get(position).getBandname());
            
            if(brandsList.get(position).getStatus() == ScanDevice.DEVICE_NONE)
                viewHolder.status.setText("未检测到");
            else if(brandsList.get(position).getStatus() == ScanDevice.DEVICE_INPUT)
                viewHolder.status.setText("已插入");
            else if(brandsList.get(position).getStatus() == ScanDevice.DEVICE_CONNECT)
                viewHolder.status.setText("已连接");
            
            if(selectPosition == position){
                Log.w(TAG, "View Select:" + namesList.get(position).getBandname());
                viewHolder.select.setChecked(true);
            }
            else{
                Log.w(TAG, "View NoSelect:" + namesList.get(position).getBandname());
                viewHolder.select.setChecked(false);
            }
            return convertView;
        }
    }
    
    public class ViewHolder{
        TextView name;
        TextView status;
        RadioButton select;
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event)  
    {  
        if ((keyCode == KeyEvent.KEYCODE_BACK ) || (keyCode == KeyEvent.KEYCODE_HOME ))
        {
            try {
                Tsexample.ts_scan_deinit();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.exit(0); 
        }
        return false;  
    }
    
}
