package com.suixingpay.serialkit.comm;

import android.util.Log;

public class CommHelper {
    private static final String TAG = "CommHelper";
    private static CommHelper instance;
    private CommInterface commInterface;

    public interface CommInterface {
        void create();

        boolean isConnect();

        void connect();

        void send(byte[] data);

        byte[] recvNonBlocking();

        void disConnect();
        
        void setRecvTimeout(int timeout);

        int getRecvTimeout();
    }

    private CommHelper() {
    }

    public static CommHelper getInstance() {
        if (instance == null) {
            instance = new CommHelper();
        }
        return instance;
    }

    public void setCommInterface(CommInterface comm) {
        this.commInterface = comm;
    }

    public void create() {
        if (commInterface != null) {
            commInterface.create();
        } else {
            logError("CommInterface not set!");
        }
    }

    public boolean isConnect() {
        return commInterface != null && commInterface.isConnect();
    }

    public void connect() {
        if (commInterface != null) {
            commInterface.connect();
        } else {
            logError("CommInterface not set!");
        }
    }

    public void send(byte[] data) {
        if (commInterface != null) {
            commInterface.send(data);
        } else {
            logError("CommInterface not set!");
        }
    }

    public byte[] recvNonBlocking() {
        if (commInterface != null) {
            return commInterface.recvNonBlocking();
        } else {
            logError("CommInterface not set!");
            return null;
        }
    }

    public void disConnect() {
        if (commInterface != null) {
            commInterface.disConnect();
        } else {
            logError("CommInterface not set!");
        }
    }

    public void setRecvTimeout(int timeout) {
        if (commInterface != null) {
            commInterface.setRecvTimeout(timeout);
        } else {
            logError("CommInterface not set!");
        }
    }

    public int getRecvTimeout() {
        return commInterface != null ? commInterface.getRecvTimeout() : 20000;
    }

    private void logInfo(String msg) {
        Log.i(TAG, msg);
    }

    private void logError(String msg) {
        Log.e(TAG, msg);
    }


}
