package chaoran.business.adapter;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2021-02-01          FXY        Created
 **********************************************
 */


import android.content.Context;
import android.os.Build;

import chaoran.business.activity.ResultListener;
import chaoran.business.strategy.Strategy;

import java.io.*;

/**
 * 瑞芯适配器
 */
public class RockChipAdapter implements Adapter {

    private Strategy strategy;

    private ResultListener resultListener;

    private Context context;

    public static final String[] barcode = {""};

    @Override
    public void start() {
        strategy.executeStrategy(resultListener);
    }

    @Override
    public void stop() {
        strategy.exclusiveStrategy();
    }

    public RockChipAdapter(Context context, ResultListener resultListener) {
        this.resultListener = resultListener;
        this.context = context;
        String fileName = "/dev/ttyS1";
        if (Build.MODEL.equalsIgnoreCase("rk3568_r")) {
            fileName = "/dev/ttyS8";
        }
        this.strategy = new Reader(new File(fileName), 115200, 0);
    }

    public class Reader implements Strategy {
        private FileDescriptor mFd;
        private FileInputStream mFileInputStream;
        private boolean running = true;

        public Reader(File device, int baudrate, int flags) {

            if (!device.canRead() || !device.canWrite()) {
                try {
                    Process su;
                    su = Runtime.getRuntime().exec("/system/bin/su");
                    String cmd = "chmod 777 " + device.getAbsolutePath() + "\n" + "exit\n";
                    su.getOutputStream().write(cmd.getBytes());

                    if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                        System.out.println("获取su命令权限失败,系统或许未root！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("获取root权限失败");
                }
            }
            mFd = open(device.getAbsolutePath(), baudrate, flags);
            if (mFd == null) {
                System.out.println("获取文件描述符失败！");
            }
            mFileInputStream = new FileInputStream(mFd);
        }

        @Override
        public void executeStrategy(ResultListener resultListener) {
            running = true;
            new Thread(() -> {
                while (running) {
                    String data = data();
                    if (!data.equals("")) {
                        synchronized (RockChipAdapter.class) {
                            barcode[0] = barcode[0] + data;
                        }
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    synchronized (RockChipAdapter.class) {
                        if (!"".equals(barcode[0])) {
//                            Log.i("listen", "Thread result data: \t\t" + barcode[0] + "\t\t" + System.currentTimeMillis());
                            resultListener.result(barcode[0]);
                            barcode[0] = "";
                        }
                    }
                }
            }).start();
        }

        @Override
        public void exclusiveStrategy() {
//            running = false;
//            close();
        }

        private String data() {
            if (mFileInputStream == null) {
                return "";
            }
            synchronized (RockChipAdapter.class) {
                try {
                    int size = mFileInputStream.available();
                    byte[] buffer = new byte[size];
                    size = mFileInputStream.read(buffer);
                    if (size > 0) {
                        String data = new String(buffer);
                        return data;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return "";
        }
    }

    static {
        System.loadLibrary("rockchip");
    }

    private native static FileDescriptor open(String path, int baudrate, int flags);

    public native void close();
}
