package com.miya.print;

import android.content.Context;

import com.miya.print.utils.D;

/**
 * 打印机管理者
 */
public class PrinterManager {

    final static String TAG = PrinterManager.class.getSimpleName();

    /**
     * 设备类型枚举，用于轮询过程中的反射
     */
    enum Type {
        //这里添加扩展的驱动
//        TYPE_HISENSE("hisense", ChuangjiePrinter.class.getName()),
//        TYPE_YINGTAI("yingtai", ChuangjiePrinter.class.getName()),
//        TYPE_SUNMI("shangmi", ChuangjiePrinter.class.getName()),
        TYPE_CHUANGJIE("chuangjie", ChuangjiePrinter.class.getName());

        /**
         * 设备类型名称
         */
        String typeName;

        /**
         * 设备驱动类全类名
         */
        String clsName;

        Type(String typeName, String clsName) {
            this.typeName = typeName;
            this.clsName = clsName;
        }

        @Override
        public String toString() {
            return "Type{" +
                    "typeName='" + typeName + '\'' +
                    ", clsName='" + clsName + '\'' +
                    '}';
        }
    }

    public static PrinterManager instance;

    private PrinterManager() {
    }

    public static PrinterManager getInstance() {
        synchronized (PrinterManager.class) {
            if (instance == null) {
                instance = new PrinterManager();
            }
            return instance;
        }
    }

    /**
     * 打印机器
     */
    IPrinter printer;

    /**
     * 轮询初始化
     *
     * @return 状态码
     */
    public boolean init(Context context) {
        for (Type type : Type.values()) {
            if (printer != null) {
                printer.release();
            }
            try {
                Class printerCls = Class.forName(type.clsName);
                printer = (IPrinter) printerCls.newInstance();
                boolean result = printer.init(context);
                if (result == true) {
                    printer.setPrinterName(type.typeName);
                    D.i(TAG, "初始化打印机成功，打印机器为：" + type.typeName);
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //没有找到对应的打印机
        if (printer != null) {
            printer.release();
        }
        D.i(TAG, "没找到对应的打印机器，请检查");
        return false;
    }

    /**
     * 获取当前打印接口
     *
     * @return
     */
    public IPrinter getPrinter() {
        return printer;
    }

    /**
     * 判断当前打印机是否已连接
     *
     * @return
     */
    public boolean isConnected() {
        return printer != null;
    }
}
