package com.qianmi.hardwarekit.sunmi.lcd;

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 android.os.SystemProperties;
import android.util.Log;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;

import woyou.aidlservice.jiuiv5.ILcdCallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

/**
 * 客显LCD包
 * 接口： 在IWoyouService.aidl中新增4个接口：
 */
public class LcdModule extends ReactContextBaseJavaModule {
    public static final String TAG = LcdModule.class.getName();
    private IWoyouService woyouService;
    private ILcdCallback callback = null;
    boolean mBound = false;
    private String model = SystemProperties.get("ro.product.model");
    public static final String DEVICES = "t2mini,t1mini";
    private boolean canUse = 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 LcdModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.canUse = DEVICES.contains(model.toLowerCase());
        Log.d(TAG, "canUse=" + this.canUse + ", " + model.toLowerCase());
    }

    @ReactMethod
    public void create() {
        if (canUse) {
            callback = new ILcdCallback.Stub() {

                /**
                 * 返回执行结果
                 * @param show:		  true 显示成功  false 显示失败
                 */
                @Override
                public void onRunResult(final boolean show) throws RemoteException {
                    Log.d(TAG, "onRunResult：" + show);
                }
            };

            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() {
        if (canUse) {
            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());
            }
        }
    }

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

    /*
     *  发送LCD控制指令
     *  @param flag 1 初始化 2 唤醒LCD 3休眠LCD 4清屏
     */
    @ReactMethod
    public void sendLCDCommand(Integer cmd) {
        Log.d(TAG, "sendLCDCommand: mBound=" + mBound + ", " + cmd.toString());
        if (canUse && mBound) {
            try {
                woyouService.sendLCDCommand(cmd);
            } catch (RemoteException e) {
                Log.e(TAG, "sendLCDCommand error: " + e.toString());
                e.printStackTrace();
            }
        }
    }

    /*
     *  发送一个字符串显示到顾显上
     *  @param string 显示的字符串内容，最多显示4个汉字或8个英文
     */
    @ReactMethod
    public void sendLCDString(String lcdStr) {
        Log.d(TAG, "sendLCDString: mBound=" + mBound + ", " + lcdStr);
        if (canUse && mBound) {
            try {
                woyouService.sendLCDString(lcdStr, callback);
            } catch (RemoteException e) {
                Log.e(TAG, "sendLCDString error: " + e.toString());
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送多行固显内容字符串
     * text: 多行固显的每行内容，每行内容可为空，此时仅占据空间
     * align: 每行固显内容所占权重
     * 支持版本: T1mini-v4.0.0以上
     * T2mini-v4.0.0以上
     * <p>
     * void sendLCDMultiString(in String[] text, in int[] align, ILcdCallback callback);
     */
    @ReactMethod
    public void sendLCDMultiString(ReadableMap paramMap) {
        ReadableArray textArray = paramMap.getArray("textArr");
        ReadableArray alignArray = paramMap.getArray("alignArray");
        if (alignArray != null && textArray != null && textArray.size() == alignArray.size()) {
            String[] textArr = new String[textArray.size()];
            int[] alignArr = new int[textArray.size()];
            for (int i = 0; i < textArray.size(); i++) {
                textArr[i] = textArray.getString(i);
                alignArr[i] = textArray.getInt(i);
            }
            Log.d(TAG, "sendLCDMultiString: mBound=" + mBound + ", " + textArr.toString());
            if (canUse && mBound) {
                try {
                    woyouService.sendLCDMultiString(textArr, alignArr, callback);
                } catch (RemoteException e) {
                    Log.e(TAG, "sendLCDMultiString error: " + e.toString());
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 发送可设置字体大小的单行固显内容字符串
     * string：显示内容
     * size：显示内容的字体大小，字体越大可显示内容越少
     * fill：当字体高度不够时是否使字体填满固显屏幕高度但宽度不变 true 填满 false 不填满（默认）
     * 支持版本: T1mini-v4.0.0以上
     * T2mini-v4.0.0以上
     * void sendLCDFillString(in String string, int size, boolean fill, ILcdCallback callback)
     */
    @ReactMethod
    public void sendLCDFillString(ReadableMap params) {
        String text = params.getString("text");
        Integer size = params.getInt("size");
        Boolean fill = params.getBoolean("fill");

        Log.d(TAG, "sendLCDFillString: mBound=" + mBound + ", " + text + ", " + size + ", " + fill);
        if (canUse && mBound) {
            try {
                woyouService.sendLCDFillString(text, size.intValue(), fill.booleanValue(), callback);
            } catch (RemoteException e) {
                Log.e(TAG, "sendLCDFillString error: " + e.toString());
                e.printStackTrace();
            }
        }
    }


    /**
     * 发送双行固显内容字符串
     * string: 固显显示的字符串
     * 支持版本：T1mini-v2.4.1以上
     * T2mini-v1.0.0以上
     * void sendLCDDoubleString(in String topText, in String bottomText, ILcdCallback callback);
     */
    @ReactMethod
    public void sendLCDDoubleString(ReadableMap params) {
        String topText = params.getString("topText");
        String bottomText = params.getString("bottomText");

        Log.d(TAG, "sendLCDDoubleString: mBound=" + mBound + ", " + topText + "," + bottomText);
        if (canUse && mBound) {
            try {
                woyouService.sendLCDDoubleString(topText, bottomText, callback);
            } catch (RemoteException e) {
                Log.e(TAG, "sendLCDFillString error: " + e.toString());
                e.printStackTrace();
            }
        }
    }

    /*
     *  发送一张图片显示到顾显上
     *  @param bitmap 显示的图片对象，大小最多为128*40像素
     * void sendLCDBitmap(in Bitmap bitmap, ILcdCallback callback);
     */
    @ReactMethod
    public void sendLCDBitmap(ReadableMap payParams, final Callback callback) throws Exception {
        throw new Exception("Not implement");
    }

}
