package jp.agentec.abook.abv.cl.util;

import android.bluetooth.BluetoothSocket;

import java.io.IOException;
import java.io.InputStream;

import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.dto.SppDeviceDto;

/**
 * 大和機器のbluetooth通信でデータを受け取るスレッド
 */
public class YamatoBluetoothReceiveTask extends Thread {
    public static final String TAG = "YamatoBluetoothReceiveTask";

    private InputStream mInputStream;

    private BluetoothSocket mSocket;

    private SppDeviceDto mSppDeviceDto;

    private static final int STX = 2;

    private static final int ETX = 3;

    private BluetoothReceiveTaskListener mListener;

    public interface BluetoothReceiveTaskListener {
        void onGetData(String result);  // 値取得時のリスナ
        void onFail(boolean dataFormatErrorFlg); // 失敗リスナ
    }

    public YamatoBluetoothReceiveTask(BluetoothSocket socket, SppDeviceDto sppDeviceDto, BluetoothReceiveTaskListener listener) {
        mSocket = null;
        mInputStream = null;
        mSppDeviceDto = sppDeviceDto;
        mListener = listener;
        if (socket == null) {
            Logger.e(TAG, "parameter socket is null.");
            mListener.onFail(false);
            return;
        }

        try {
            mSocket = socket;
            mInputStream = socket.getInputStream();
        } catch (IOException e) {
            Logger.e(TAG, e);
            mListener.onFail(false);
            return;
        }
    }

    @Override
    public void run() {
        Logger.i(TAG, "bluetoothReciveTask run");
        int readSize = 0;
        String str = "";
        while (mInputStream != null) {
            Logger.i(TAG, "start read mInputStream.");

            if (mSocket == null) {
                Logger.e(TAG, "mSocket is null.");
                break;
            }

            try {
                byte[] buffer = new byte[1024];
                readSize = mInputStream.read(buffer);
                str += new String(buffer, 0, readSize);
                Logger.i(TAG, "getData : " + str);
                if (str.indexOf(new Character((char) STX).toString()) != -1 && str.indexOf(new Character((char) ETX).toString()) != -1) {
                    String dataStr = str.substring(str.indexOf(new Character((char) STX).toString()) + 1, str.indexOf(new Character((char) ETX).toString()));
                    Logger.i(TAG, "convert data : " + dataStr);

                    String result = dataStr.substring(mSppDeviceDto.dataStartIndex - 1, mSppDeviceDto.dataEndIndex - 1).replaceAll(" ", "");
                    // データを取得したらリセット
                    str = "";
                    mListener.onGetData(result);
                }
                Thread.sleep(500);
            } catch (IndexOutOfBoundsException e) {
                Logger.e(TAG, e);
                mListener.onFail(true);
                break;
            } catch (Exception e) {
                Logger.e(TAG, e);
                mListener.onFail(false);
                break;
            }
        }
        Logger.i(TAG, "exit read task.");
    }

    /**
     * ソケットを初期化処理
     */
    public void finish() {
        if (mSocket == null) {
            return;
        }

        try {
            mSocket.close();
            mSocket = null;
        } catch (IOException e) {
            Logger.e(TAG, e);
        }
    }
}