package com.qianmi.hardwarekit.sunmi.printer;

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


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import java.lang.Exception;

import android.util.Log;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;

import java.util.StringTokenizer;

import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

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

public class WoyouPrinterModule extends ReactContextBaseJavaModule {
    private IWoyouService woyouService;
    private ICallback callback = null;
    boolean mBound = false;


    private ServiceConnection connService = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
            mBound = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService = IWoyouService.Stub.asInterface(service);
            mBound = true;

        }
    };

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

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


    @ReactMethod
    public void create() {
        callback = new ICallback.Stub() {

            @Override
            public void onRunResult(final boolean success) throws RemoteException {
            }

            @Override
            public void onReturnString(final String value) throws RemoteException {
                Log.i(getClass().getSimpleName(), "printlength:" + value + "\n");
            }

            @Override
            public void onRaiseException(int code, final String msg) throws RemoteException {
                Log.i(getClass().getSimpleName(), "onRaiseException: " + msg);
            }

            /**
             * 返回打印机结果
             * code：	异常代码 0 成功 1 失败
             * msg:	异常描述
             */
            public void onPrintResult(int code, final String msg) throws RemoteException {
                Log.i(getClass().getSimpleName(), "onPrintResult: " + msg);
            }
        };

        Intent intent = new Intent();
        intent.setPackage("woyou.aidlservice.jiuiv5");
        intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
        getReactApplicationContext().startService(intent);
        getReactApplicationContext().bindService(intent, connService, Context.BIND_AUTO_CREATE);

    }


    @ReactMethod
    public void destroy() {
        Intent intent = new Intent();
        intent.setPackage("woyou.aidlservice.jiuiv5");
        intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
        getReactApplicationContext().stopService(intent);

        try {
            if (mBound) {
                getReactApplicationContext().unbindService(connService);
            }
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }

    
    /**
     * 获取打印机型号
     */
    @ReactMethod
    public void getPrinterModal(Promise promise){
        try {
            String printerModal = woyouService.getPrinterModal();
            WritableMap map = Arguments.createMap();
            map.putString("value", printerModal.trim());
            Log.d("QianmiPrint:getPrinterModal", printerModal);
            promise.resolve(map);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.toString());
            promise.reject("-1", e.toString());
        }
    }

    @ReactMethod
    public void printColumnsText(String text, String width, String align) {

        String[] ws = width.split(",");
        String[] as = align.split(",");
        try {
            woyouService.printColumnsText(substring(text.split(",")), toInts(ws), toInts(as), callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }

    //0x1d 0x56 0x42 0x00
    @ReactMethod
    public void cutAll() {
        try {
            woyouService.sendRAWData(new byte[]{(byte) 0x1d, (byte) 0x56, (byte) 0x42, (byte) 0x00}, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }

    //0x10 0x14 0x00 0x00 0x00
    @ReactMethod
    public void openBox() {
        try {
            woyouService.openDrawer(callback);
            // woyouService.sendRAWData(new byte[]{(byte) 0x10, (byte) 0x14, (byte) 0x00, (byte) 0x00, (byte) 0x00}, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }

    /**
     * 对齐方式 0--居左 , 1--居中, 2--居右
     *
     * @param alignment
     */
    @ReactMethod
    public void setAlignment(Integer alignment) {
        try {
            woyouService.setAlignment(alignment, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    /**
     * 设置字体大小
     *
     * @param alignment
     */
    @ReactMethod
    public void setFontSize(Integer alignment) {
        try {
            woyouService.setFontSize(alignment, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    /**
     * 使用原始指令打印
     *
     * @param command
     */
    @ReactMethod
    public void sendRAWData(String command) {

        StringTokenizer stringTokenizer = new StringTokenizer(command, ",");

        byte[] datas = new byte[]{};

        for (int index = 0; index < stringTokenizer.countTokens(); ++index) {
            datas[index] = Byte.parseByte(stringTokenizer.nextElement().toString());
        }

        try {
            woyouService.sendRAWData(datas, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    //打印一维码
    @ReactMethod
    public void printBarCode(String data) {
        try {
            woyouService.setAlignment(1, callback);
            woyouService.printBarCode(data, 8, 120, 2, 2, callback);
            woyouService.lineWrap(3, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    //空白
    @ReactMethod
    public void lineWrap(Integer nums) {
        try {
            woyouService.lineWrap(nums, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    //打印文字
    @ReactMethod
    public void printlnText(String text) {
        try {
            woyouService.printText(text + "\n", callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    //打印文字
    @ReactMethod
    public void printText(String text) {
        try {
            woyouService.printText(text, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    //打印文字
    @ReactMethod
    public void printTextWithFont(String text, String typeface, Float fontSize) {
        try {
            woyouService.printTextWithFont(text, typeface, fontSize, callback);
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
        }
    }


    @ReactMethod
    public void printQCode(final String url, final Promise promise) {
        final WritableMap params = Arguments.createMap();
        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    woyouService.setAlignment(1, callback);
                    byte[] bytes = BytesUtil.getZXingQRCode(url, 330);
                    System.out.println(BytesUtil.getHexStringFromBytes(bytes));
                    woyouService.sendRAWData(bytes, new ICallback.Stub() {

                        @Override
                        public void onRunResult(final boolean success) {
                            params.putBoolean("value", success);
                            promise.resolve(params);
                        }

                        @Override
                        public void onReturnString(final String value) {
                            Log.i(getClass().getSimpleName(), "printlength:" + value + "\n");
//                            params.putBoolean("value", true);
//                            promise.resolve(params);
                        }

                        @Override
                        public void onRaiseException(int code, final String msg) {
                            Log.i(getClass().getSimpleName(), "onRaiseException: " + msg);
                            params.putBoolean("value", false);
                            promise.resolve(params);
                        }

                         /**
                         * 返回打印机结果
                         * code：	异常代码 0 成功 1 失败
                         * msg:	异常描述
                         */
                        public void onPrintResult(int code, final String msg) {
                            Log.i(getClass().getSimpleName(), "onPrintResult: " + msg);
                            params.putInt("value", code);
                            promise.resolve(params);
                        }
                    });
                    woyouService.lineWrap(3, callback);

                } catch (Exception e) {
                    Log.e(getClass().getSimpleName(), e.getClass().getSimpleName());
                    params.putBoolean("value", false);
                }
            }
        });
    }


    private int[] toInts(Object[] arrs) {
        int[] a = new int[arrs.length];
        for (int index = 0; index < arrs.length; ++index) {
            a[index] = Integer.valueOf(arrs[index].toString());
        }

        return a;
    }

    private String[] substring(String[] strings) {
        for (int index = 0; index < strings.length; ++index) {
            String s = strings[index];
            String temp = "";
            if (s.length() > 12) {
                temp = s.substring(0, 11);
                temp = temp.replace("�", "");
            } else {
                temp = s;
            }

            strings[index] = temp;
        }
        return strings;
    }
}
