package com.qianmi.hardwarekit.sunmi.printer;

/**
 * Created by xiayinglin on 2017/4/6.
 */


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.widget.Toast;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.io.IOException;

/**
 * Created by cyz.aoj on 2017/1/16.
 */

public class BluetoothPrinterModule extends ReactContextBaseJavaModule {


    public BluetoothPrinterModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "SUNMIBluetoothPrinter";
    }


    @ReactMethod
    public  void write() {
        BluetoothAdapter btAdapter = BluetoothUtil.getBTAdapter();
        if (btAdapter == null) {
            Toast.makeText(getReactApplicationContext(), "Please Open Bluetooth!", Toast.LENGTH_LONG).show();
            return;
        }
        BluetoothDevice device = BluetoothUtil.getDevice(btAdapter);
        if (device == null) {
            Toast.makeText(getReactApplicationContext(), "Please Make Sure Bluetooth have InnterPrinter!", Toast.LENGTH_LONG).show();
            return;
        }
        // 3: Generate a order data
        byte[] data = ESCUtil.generateMockData();
        // 4: Using InnerPrinter print data
        BluetoothSocket socket = null;
        try {
            socket = BluetoothUtil.getSocket(device);
            BluetoothUtil.sendData(data, socket);
        } catch (IOException e) {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}