package com.example.administrator.wingcool_gt9_apk;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 */

public class UsbSetting extends AppCompatActivity
        //implements OpenDevicesReceiver.OpenDevicesListener, View.OnClickListener , ViewPager.OnPageChangeListener, AdapterView.OnItemSelectedListener{
        implements OpenDevicesReceiver.OpenDevicesListener, View.OnClickListener , ViewPager.OnPageChangeListener{
    private static final int CONNECTED_SUCCESS = 0;
    private static final int RECEIVER_MESSAGE_SUCCESS = 1;
    private static final int SEND_MESSAGE_SUCCESS = 2;
    private static final int DEBUG_MESSAGE_SUCCESS = 3;
    private static final int DEBUG_MESSAGE_ERROR = 4;

    private static final String USB_ACTION = "com.host2device";
    private static final String ACTION_USB_PERMISSION = "com.host2device.USB_PERMISSION";
    private ExecutorService mThreadPool;
    private UsbManager mUsbManager;
    private OpenDevicesReceiver cfgOpenDevicesReceiver;
    private UsbDeviceConnection mUsbDeviceConnection;

    private UsbEndpoint mUsbEndpointOut;
    private UsbEndpoint mUsbEndpointIn;
    private int iProductId;
    private byte byProductType = 0;
    private static final byte GT9 = 0x01;
    private static final byte GT7 = 0x02;
    private Button mReadCfg;
    private Button mSendCfg;
    private byte[] mBytes = new byte[1024];
    private byte[] mSendData = new byte[1024];

    private Context mAlertContext;

    String value;

    private boolean isNeedFindDevice  = true;

    private int bottonMode = 0;

    private UsbInterface mUsbInterface;
    private StringBuffer mStringBuffer = new StringBuffer();
    private Context mContext;

    private TextView mShow;
    private TextView tvVenderID;

    //View Usb Setting 定义
    private Spinner spinInterface;
    private CheckBox cbMouseRightClickDis,cbMouseDoubleClickEn,cbWakeUpEn;
    private Spinner spinReportType,spinUartProtocal;
    private EditText edtVID,edtPID;  //2 bytes
    private Spinner spinUartBuad;
    private CheckBox cbLongPressRightKeyEn;
    private EditText edtDimensionX,edtDimensionY,edtUSBResolutionX,edtUSBResolutionY;  //2 bytes

    private ViewPager vpagerCfg;
    private ImageView img_cursor;
    private TextView tvUsbSetting;

    private ArrayList<View> listViews;
    View viewusbsetting;

    private int offset = 0;//移动条图片的偏移量
    private int currIndex = 0;//当前页面的编号
    private int bmpWidth;// 移动条图片的长度
    private int one = 0; //移动条滑动一页的距离
    private int two = 0; //滑动条移动两页的距离
    private int three = 0; //滑动条移动三页的距离
    private int four = 0; //滑动条移动四页的距离
    private int five = 0; //滑动条移动五页的距离
    private int six = 0; //滑动条移动六页的距离
    private int seven = 0; //滑动条移动七页的距离
    private int eight = 0; //滑动条移动八页的距离
    private int nine = 0; //滑动条移动九页的距离
    private int iChooseVPager = 0; //当前停在哪个vpager

    private byte mSendGetGt9ConfigData[]={
            0x03,0x00,0x0f,(byte)0x80,0x47,0x00,0x3f,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    };

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            StringBuilder stringBuilder = new StringBuilder("");
            StringBuffer resultSb = new StringBuffer();
            // for (int i = 1; i < mBytes.length; i++) {
            int checksum = 0 ;
            switch (msg.what) {
                case CONNECTED_SUCCESS://车机和手机连接成功
                    //mError.setText("");
                    mReadCfg.setEnabled(true);
                    mSendCfg.setEnabled(true);
                    break;

                case RECEIVER_MESSAGE_SUCCESS://成功接受到数据

                    break;

                case SEND_MESSAGE_SUCCESS://成功发送数据
                    //mMessage.setText("");
                    break;

                case DEBUG_MESSAGE_SUCCESS://成功发送数据
                    //StringBuilder stringBuilder = new StringBuilder("");
                   // StringBuffer resultSb = new StringBuffer();

                    checksum = 0 ;
                    for (int i = 0; i < 216; i++) {

                        int v = mSendData[i] & 0xFF;
                        checksum =checksum+ v;
                        //byte v = mSendData[i];
                        String hv = Integer.toHexString(v);
                        //String hv = Byte.toString(v);
                        stringBuilder.append(hv);
                        stringBuilder.append(",");
                    }
                    //mShow.setText(stringBuilder.toString());
                    //mShow.setText(value);
                    break;
                case DEBUG_MESSAGE_ERROR://成功发送数据
                    //mShow.setText("ERROR");
                    //mError.setText("ERROR");
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbsetting);
        mAlertContext = UsbSetting.this;
        ConstantsActivity.activityList.add(this);
        //switchLanguage(ConstantsActivity.langae);
        init();
    }

    //核心设置的代码
    protected void switchLanguage(String language) {
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = Locale.CHINESE;
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = Locale.ENGLISH;
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = Locale.US;
                resources.updateConfiguration(config, dm);
                break;
        }
    }

    private void init() {
        initView();
        initViewPager();
        initUsbSpin();
        initListener();
        initData();
        openDevices();
    }

    private void initView() {
        mReadCfg = (Button) findViewById(R.id.readcfg);
        mSendCfg = (Button) findViewById(R.id.sendcfg);
        mShow = (TextView) findViewById(R.id.show);

        tvVenderID = (TextView) findViewById(R.id.venderid);
    }

    private void initViewPager() {
        vpagerCfg = (ViewPager) findViewById(R.id.vpagercfg);

        tvUsbSetting = (TextView) findViewById(R.id.tvusbsetting);


        img_cursor = (ImageView) findViewById(R.id.img_cursor);

        //下划线动画的相关设置：
        bmpWidth = BitmapFactory.decodeResource(getResources(), R.mipmap.line).getWidth();// 获取图片宽度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        //offset = (screenW / 3 - bmpWidth) / 2;// 计算偏移量
        offset = (screenW / 9 - bmpWidth) / 2;// 计算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        img_cursor.setImageMatrix(matrix);// 设置动画初始位置
        //移动的距离
        one = offset * 2 + bmpWidth;// 移动一页的偏移量,比如1->2,或者2->3
        two = one * 2;// 移动两页的偏移量,比如1直接跳3
        three = one * 3;// 移动两页的偏移量,比如1直接跳3
        four = one * 4;// 移动两页的偏移量,比如1直接跳3
        five = one * 5;// 移动两页的偏移量,比如1直接跳3
        six = one * 6;// 移动两页的偏移量,比如1直接跳3
        seven = one * 7;// 移动两页的偏移量,比如1直接跳3
        eight = one * 8;// 移动两页的偏移量,比如1直接跳3
        nine = one * 9;// 移动两页的偏移量,比如1直接跳3

        //往ViewPager填充View，同时设置点击事件与页面切换事件
        listViews = new ArrayList<View>();

        //LayoutInflater mInflater = getLayoutInflater();
        viewusbsetting = View.inflate(this,R.layout.view_usb_setting, null);

        //listViews.add(mInflater.inflate(R.layout.view_one, null, false));
        //listViews.add(mInflater.inflate(R.layout.view_two, null, false));
        //listViews.add(mInflater.inflate(R.layout.view_three, null, false));

        listViews.add(viewusbsetting);

        vpagerCfg.setAdapter(new MyPagerAdapter(listViews));
        vpagerCfg.setCurrentItem(0);          //设置ViewPager当前页，从0开始算

        tvUsbSetting.setOnClickListener(this);

        vpagerCfg.addOnPageChangeListener(this);
    }

    //===============================各view中的元素初始化开始===============================================//
    private void initUsbSpin() {
        spinInterface = viewusbsetting.findViewById(R.id._interface);
        cbMouseRightClickDis = viewusbsetting.findViewById(R.id.mouserightclickdis);
        cbMouseDoubleClickEn = viewusbsetting.findViewById(R.id.mousedoubleclicken);
        cbWakeUpEn = viewusbsetting.findViewById(R.id.wakeupen);
        spinReportType = viewusbsetting.findViewById(R.id.reporttype);
        spinUartProtocal = viewusbsetting.findViewById(R.id.uartprotocal);

        edtVID = viewusbsetting.findViewById(R.id.vid);
        edtPID = viewusbsetting.findViewById(R.id.pid);

        spinUartBuad = viewusbsetting.findViewById(R.id.uartbuad);

        cbLongPressRightKeyEn = viewusbsetting.findViewById(R.id.longpressrightkeyen);

        edtDimensionX = viewusbsetting.findViewById(R.id.dimensionx);
        edtDimensionY = viewusbsetting.findViewById(R.id.dimensiony);
        edtUSBResolutionX = viewusbsetting.findViewById(R.id.usbresolutionx);
        edtUSBResolutionY = viewusbsetting.findViewById(R.id.usbresolutiony);
    }

    //===============================各view中的元素初始化结束===============================================//

    private void initListener() {
        mReadCfg.setOnClickListener(this);
        mSendCfg.setOnClickListener(this);
    }

    private void initData() {
        mContext = getApplicationContext();
        mReadCfg.setEnabled(false);    //

        mSendCfg.setEnabled(false);

        mThreadPool = Executors.newFixedThreadPool(5);

        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    }

    /**
     * 打开设备 , 让车机和手机端连起来
     */
    private void openDevices() {

        //列举设备(手机)
        cfgOpenDevicesReceiver = new OpenDevicesReceiver(this);
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
            SystemClock.sleep(1000);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
            IntentFilter intentFilter = new IntentFilter(USB_ACTION);

            registerReceiver(cfgOpenDevicesReceiver, intentFilter);
        while(isNeedFindDevice) {
            SystemClock.sleep(100);
            HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
            if (deviceList != null) {
                for (UsbDevice usbDevice : deviceList.values()) {
                    //int productId = usbDevice.getProductId();
                    int vendorId = usbDevice.getVendorId();
                    if ((vendorId == 0x27C0)          //之前VID错误了，做兼容
                            ||(vendorId == 0x27C6)    //汇顶的VID
                            ||(vendorId == 0x222A)    //奕力的VID
                            ||(vendorId == 0x056A))   //8191主动笔和Wacom主动笔
                    {
                        //这里说明下,这里的377 , 7205是我这台机子上独有,因为我这上面有多台设备,所以我在这里
                        //判断了下.只有一台设备的无需这一步.
                        //mUsbManager.requestPermission(usbDevice, pendingIntent);
                        //SystemClock.sleep(100);
                        if (mUsbManager.hasPermission(usbDevice)) {
                                    initDevice();

                                } else {
                                    mUsbManager.requestPermission(usbDevice, pendingIntent);
                                    break;
                                }
                                break;
                            }
                        }
                    } else {
                        //mError.setText("请连接USB");
                    }
                    // }
                }
            }   //ThreadPool
        });   //ThreadPool
    }

    /**
     * 初始化设备(手机) , 当手机进入Accessory模式后 , 手机的PID会变为Google定义的2个常量值其中的一个 ,
     */
    private void initDevice() {

        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        Collection<UsbDevice> values = deviceList.values();
        if (!values.isEmpty()) {
            for (UsbDevice usbDevice : values) {
                //int productId = usbDevice.getProductId();
                int vendorId = usbDevice.getVendorId();
                //if (productId == 0x0818 || productId == 0x0001 )
                if ((vendorId == 0x27C0)          //之前VID错误了，做兼容
                        ||(vendorId == 0x27C6)    //汇顶的VID
                        ||(vendorId == 0x222A)    //奕力的VID
                        ||(vendorId == 0x056A))   //8191主动笔和Wacom主动笔
                {
                    if (mUsbManager.hasPermission(usbDevice)) {

                        UsbInterface usbInterface = usbDevice.getInterface(1);

                        for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
                            UsbEndpoint ep = usbInterface.getEndpoint(i);

                            if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                                //mUsbEndpointIn = ep;
                                mUsbEndpointOut = ep;
                            } else {
                                //mUsbEndpointOut = ep;
                                mUsbEndpointIn = ep;
                            }
                        }

                        if ((null == mUsbEndpointIn) || (null == mUsbEndpointOut)) {
                            mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);
                            if (mUsbDeviceConnection!=null) {
                                int i = mUsbDeviceConnection.controlTransfer(0x00, 0x09,
                                        0x002, 0, null, 0, 100);
                                SystemClock.sleep(1000);
                                if (i >= 0) {
                                    //mHandler.sendEmptyMessage(DEBUG_MESSAGE_SUCCESS);
                                } else {
                                    //mHandler.sendEmptyMessage(DEBUG_MESSAGE_ERROR);
                                }
                            }
                        } else {
                            isNeedFindDevice = false;
                            mUsbInterface = usbInterface;
                            mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);
                            mUsbDeviceConnection.claimInterface(mUsbInterface, true);
                            if(null != mUsbEndpointIn){
                                iProductId = usbDevice.getProductId();
                                if ((iProductId == 0x0819) || (iProductId == 0x8191) || (iProductId == 0x0528) || (iProductId == 0x0928) )
                                {
                                    byProductType = GT7;
                                }
                                else{
                                    byProductType = GT9;
                                }
                                mHandler.sendEmptyMessage(CONNECTED_SUCCESS);
                            }


                        }
                    } else {
                        mUsbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(mContext, 0, new Intent(""), 0));
                    }
                }
            }
        } else {
            // finish();
        }
    }

    //=====================================读取CFG到各个View开始===================================//
    public void ReadCfgUsb(byte[] mBytes){
        int temp;

        spinInterface.setSelection(mBytes[1] & 0x01);

        cbMouseRightClickDis.setChecked(false);
        if ((mBytes[1] & 0x02) == 0x02){
            cbMouseRightClickDis.setChecked(true);
        }
        cbMouseDoubleClickEn.setChecked(false);
        if ((mBytes[1] & 0x04) == 0x04){
            cbMouseDoubleClickEn.setChecked(true);
        }
        cbWakeUpEn.setChecked(false);
        if ((mBytes[1] & 0x08) == 0x08){
            cbWakeUpEn.setChecked(true);
        }

        spinReportType.setSelection((mBytes[1] & 0x30) >> 4);
        spinUartProtocal.setSelection((mBytes[1] & 0xC0) >> 6);

        temp = (int)((mBytes[3] & 0xFF) + mBytes[2] * 256);
        edtVID.setText(Integer.toHexString(temp & 0xFFFF));

        temp = (int)((mBytes[5] & 0xFF) + mBytes[4] * 256);
        edtPID.setText(Integer.toHexString(temp & 0xFFFF));

        spinUartBuad.setSelection(mBytes[6] & 0x03);

        cbLongPressRightKeyEn.setChecked(false);
        if ((mBytes[7] & 0x01) == 0x01){
            cbLongPressRightKeyEn.setChecked(true);
        }

        temp = (int)((mBytes[9] & 0xFF) + mBytes[8] * 256);
        edtDimensionX.setText(Integer.toString(temp & 0xFFFF));
        temp = (int)((mBytes[11] & 0xFF) + mBytes[10] * 256);
        edtDimensionY.setText(Integer.toString(temp & 0xFFFF));
        temp = (int)((mBytes[13] & 0xFF) + mBytes[12] * 256);
        edtUSBResolutionX.setText(Integer.toString(temp & 0xFFFF));
        temp = (int)((mBytes[15] & 0xFF) + mBytes[14] * 256);
        edtUSBResolutionY.setText(Integer.toString(temp & 0xFFFF));
    }

    //=====================================读取CFG到各个View结束===================================//

    //======================================合并配置开始===========================================//
    public void CombineCfg(){

        for (int i = 0; i < 24; i++){
            mBytes[i] = 0;
        }

        mBytes[0] = 24;//(byte)Integer.parseInt(edtConfigVersion.getText().toString(),10);

        //mBytes[1]
        mBytes[1] = (byte)spinInterface.getSelectedItemPosition();
        if (cbMouseRightClickDis.isChecked()){
            mBytes[1] += 2;
        }
        if (cbMouseDoubleClickEn.isChecked()){
            mBytes[1] += 4;
        }
        if (cbWakeUpEn.isChecked()){
            mBytes[1] += 8;
        }
        mBytes[1] += (byte)(spinReportType.getSelectedItemPosition() * 16);
        mBytes[1] += (byte)(spinUartProtocal.getSelectedItemPosition() * 64);

        mBytes[2] = (byte)(Integer.parseInt(edtVID.getText().toString(),16) >> 8 );  //High byte
        mBytes[3] = (byte)(Integer.parseInt(edtVID.getText().toString(),16) & 0x00ff);

        mBytes[4] = (byte)(Integer.parseInt(edtPID.getText().toString(),16) >> 8 );  //High byte
        mBytes[5] = (byte)(Integer.parseInt(edtPID.getText().toString(),16) & 0x00ff);

        mBytes[6] = (byte)spinUartBuad.getSelectedItemPosition();

        //mBytes[7]
        if (cbLongPressRightKeyEn.isChecked()){
            mBytes[7] = 1;
        }

        mBytes[8] = (byte)(Integer.parseInt(edtDimensionX.getText().toString(),10) >> 8 );  //High byte
        mBytes[9] = (byte)(Integer.parseInt(edtDimensionX.getText().toString(),10) & 0x00ff);

        mBytes[10] = (byte)(Integer.parseInt(edtDimensionY.getText().toString(),10) >> 8 );  //High byte
        mBytes[11] = (byte)(Integer.parseInt(edtDimensionY.getText().toString(),10) & 0x00ff);

        mBytes[12] = (byte)(Integer.parseInt(edtUSBResolutionX.getText().toString(),10) >> 8 );  //High byte
        mBytes[13] = (byte)(Integer.parseInt(edtUSBResolutionX.getText().toString(),10) & 0x00ff);

        mBytes[14] = (byte)(Integer.parseInt(edtUSBResolutionY.getText().toString(),10) >> 8 );  //High byte
        mBytes[15] = (byte)(Integer.parseInt(edtUSBResolutionY.getText().toString(),10) & 0x00ff);

        int checksum = 0;
        for (int i = 0; i < 22; i++) {
            int k = mBytes[i] & 0xFF;
            checksum = checksum + k;
        }
        mBytes[22] = (byte)(checksum >> 8);

        mBytes[23] = (byte)(checksum & 0xFF);

    }
    //======================================合并配置结束===========================================//

    @Override
    public void onClick(final View v) {

        switch (v.getId()) {
            case R.id.tvusbsetting:
            //case R.id.tvsample:
                vpagerCfg.setCurrentItem(0);
                iChooseVPager = 0;
                break;

            case R.id.sendcfg:   //send cfg
                bottonMode = 1;

                CombineCfg();
                //iicWrite((byte)0x81, (byte)0x40, (byte)49, mBytes, 0,24);
                iicWrite32Bits((byte)0x01, (byte)0x01, (byte)0x74, (byte)49, mBytes,0,24);

                mShow.setText("Send cfg success!!");
                break;
            case R.id.readcfg:  //read cfg
                bottonMode = 2;
                mSendData = mSendGetGt9ConfigData;

                //iicRead((byte)0x81, (byte)0x40, (byte)48, mBytes, 24);
                iicRead32Bits((byte)0x01, (byte)0x00, (byte)0x1E, (byte)48, mBytes, 24);

                ReadCfgUsb(mBytes);

                mShow.setText("Read cfg success!!");
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageSelected(int index) {

        Animation animation = null;
        switch (index) {
            case 0:
                /*
                if (currIndex == 1) {
                    animation = new TranslateAnimation(one, 0, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, 0, 0, 0);
                }
                */
                animation = new TranslateAnimation(one * currIndex, 0, 0, 0);
                break;
            case 1:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, one, 0, 0);
                } else {// if (currIndex == 2) {
                    //animation = new TranslateAnimation(two, one, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, one, 0, 0);
                }
                break;
            case 2:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, two, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, two, 0, 0);
                }
                break;
            case 3:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, three, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, three, 0, 0);
                }
                break;
            case 4:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, four, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, four, 0, 0);
                }
                break;
            case 5:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, five, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, five, 0, 0);
                }
                break;
            case 6:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, six, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, six, 0, 0);
                }
                break;
            case 7:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, seven, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, seven, 0, 0);
                }
                break;
            case 8:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, eight, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, eight, 0, 0);
                }
                break;
            case 9:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, nine, 0, 0);
                } else {//if (currIndex == 1) {
                    //animation = new TranslateAnimation(one, two, 0, 0);
                    animation = new TranslateAnimation(one * currIndex, nine, 0, 0);
                }
                break;
            default:
                break;
        }
        currIndex = index;
        animation.setFillAfter(true);// true表示图片停在动画结束位置
        animation.setDuration(300); //设置动画时间为300毫秒
        img_cursor.startAnimation(animation);//开始动画
        iChooseVPager = index; //获取当前Vpager的索引，以便知道在哪个pager
    }

    @Override
    public void onPageScrollStateChanged(int i) {
        switch (i){
            case 0:

                break;
            case 1:

                break;
            case 2:

                break;
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {
        //edtshow3.setText("333");
        switch (i){
            case 0:

                break;
            case 1:

                break;
            case 2:
                break;
        }
    }

    private byte iicByteData[]={
            //0    1   2     3    4    5    6
            0x03,0x00,0x0f,0x00,0x00,0x00,0x01,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,

    };
    private byte iicWriteData[]={
            //0    1   2     3    4    5    6
            0x03,0x00,0x0f,0x00,0x00,0x00,0x39,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,

    };

    //发送命令，使得S8xx可以通过IIC向GT29xx的固定地址读取任意bytes的数据
    private boolean iicRead32Bits(byte addrfirstbyte,byte addrsecondbyte,byte addrthirdbyte,byte subCommand,byte[] wBuffer,int length) {

        int i;

        iicByteData[1] = (byte)(0 | subCommand);//0x0f; //7bit:0-read,1-write;other:command
        //iicByteData[2] = 0x0f; //no command
        iicByteData[2] = addrfirstbyte;
        iicByteData[3] = addrsecondbyte;
        iicByteData[4] = addrthirdbyte;
        iicByteData[5] = 0x00;
        iicByteData[6] = 63;  //length 一次接收63个数据

        for (int j = 7; j < 64; j++) {
            iicByteData[j] = 0x00;
        }

        int address1 = ((addrsecondbyte & 0xff) << 8);
        int address2 = addrthirdbyte & 0xff;
        int address = address1 | address2;

        int sendTimes = length / 63;  //预计是向下取整，所以+1

        if ((length % 63) != 0)
        {
            sendTimes += 1;   //预计是向下取整，所以+1
        }
        //iicByteData[5] = (byte)(length>>8);
        //iicByteData[6] = (byte)length;  //length 一次接收63个数据

        for (int k = 0; k < sendTimes; k++)
        {
            int finalOffset = k*63; //每次只能发57bytes数据
            int offset = k * 64;

            if(length - (finalOffset ) < 63) {

                iicByteData[6] = (byte) (length - (finalOffset));  //length
            }
            else
            {
                iicByteData[6] = 63;
            }

            //发送读取命令
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicByteData, 0, 0x40, 100);
            if (i != 0x40)
                return false;  //传输失败

            // SystemClock.sleep(1);

            //接收数据
            // i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, wBuffer, offset, 0x40, 100);
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, wBuffer, offset, 0x40, 100);

            //if (i != 0x40) {
            if (i != 0x40) {
                //editname.setText("IIC Read Failed!!");
                return false;

            }

            address = address + 63;
            iicByteData[3] = (byte)(address>>8);
            iicByteData[4] = (byte)address;
        }

        //将report id从数组中去除
        //byte[] temperBuffer =new byte[length];
        if(true) {
            int count1 = 0;
            for (int k = 0; k < length; k++) {
                if (k % 63 == 0) {
                    count1++;
                }

                wBuffer[k] = wBuffer[k + count1];

            }
        }
        return true;
    }
    //发送命令，使得S8xx可以通过IIC向GT79xx的固定地址写任意bytes的数据
    private  boolean iicWrite32Bits(byte addrfirstbyte,byte addrsecondbyte,byte addrthirdbyte,byte subCommand,byte[] wBuffer,int offset, int length) {

        int i;

        iicWriteData[1] = (byte)(0x80 | subCommand);//0x0f; //7bit:0-read,1-write;other:command
        //iicWriteData[2] = 0x0f; //no command
        iicWriteData[2] = addrfirstbyte;
        iicWriteData[3] = addrsecondbyte;
        iicWriteData[4] = addrthirdbyte;
        iicWriteData[5] = 0x00;
        iicWriteData[6] = 63;  //length 一次接收63个数据

        for (int j = 7; j < 64; j++) {
            iicWriteData[j] = 0x00;
        }

        int address1 = ((addrsecondbyte&0xff)<<8);
        int address2 = addrthirdbyte&0xff;
        int address = address1|address2;

        int sendTimes = length/57 + 1;  //预计是向下取整，所以+1

        //iicByteData[5] = (byte)(length>>8);
        //iicByteData[6] = (byte)length;  //length 一次接收63个数据

        for (int k = 0; k < sendTimes; k++) {
            int finalOffset = offset + k*57; //每次只能发57bytes数据

            if(length - (finalOffset -offset) < 57) {

                iicWriteData[6] = (byte) (length - (finalOffset -offset));  //length
            }
            else
            {
                iicWriteData[6] = 0x39;
            }

            for (int j = 7; j < 64; j++) {
                iicWriteData[j] = wBuffer[finalOffset + j -7];
            }
            i = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, iicWriteData, 0, 0x40, 100);

            if (i != 0x40) {
                mShow.setText("iicWrite Failed");
                return false;

            }

            address = address + 57;
            //iicWriteData[2] = (byte)((address & 0xFF0000) >> 16);
            iicWriteData[3] = (byte)(address >> 8);
            iicWriteData[4] = (byte)address;
        }

        return true;
    }

    boolean memCmp(byte[] sBuffer,byte[] dBuffer,int offset,int length) {
        try {

            for (int i = 0; i < length; i++) {
                if (sBuffer[i] != dBuffer[offset + i]) {
                    // FwUpdateMessage(L"Recall frame data fail,not equal.", MSG_ERR);
                    // mError.setText("Recall frame data fail,not equal.");
                    return false;
                }
            }
        } catch (ArithmeticException e) {
            mShow.setText("ArithmeticException!");
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            mShow.setText("ArrayIndexOutOfBoundsException!");
            e.printStackTrace();
        }

        return true;
    }
/*
    boolean recallCheck(byte addressHigh,byte addressLow,byte[] wBuffer,int offset,int length)
    {
        //BYTE* pbBuf = new BYTE[wLen];
        byte[] pbBuf =new byte[length+0x3000];

        //if(false)
        {
            if (!iicRead(addressHigh, addressLow, (byte)0x0f, pbBuf, length)) {
                //FwUpdateMessage(L"recall i2c error failed", MSG_ERR);
                mShow.setText("recall i2c error failed");
                return false;
            }
            if (!memCmp(pbBuf, wBuffer, offset, length)) {

                // FwUpdateMessage(L"Recall frame data fail,not equal.", MSG_ERR);
                //mMessage.setText("Recall frame data fail,not equal.");
                return false;
            }
        }
        return true;

    }
*/
    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mUsbDeviceConnection != null) {
            mUsbDeviceConnection.releaseInterface(mUsbInterface);
            mUsbDeviceConnection.close();
            mUsbDeviceConnection = null;
        }
        mUsbEndpointIn = null;
        mUsbEndpointOut = null;
        isNeedFindDevice = false;
        mThreadPool.shutdownNow();
       // unregisterReceiver(mUsbDetachedReceiver);
        unregisterReceiver(cfgOpenDevicesReceiver);
    }
}

