package com.miya.print;

import android.content.Context;

import com.miya.print.utils.PrintLogger;

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

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

    /**
     * 设备类型枚举，用于轮询过程中的反射
     */
    public enum Type {
        //这里添加扩展的驱动
        TYPE_HISENSE("hisense", HisensePrinter.class.getName()),
        TYPE_SUNMI_TI("sunmiT1", SunmiT1Printer.class.getName()),
        TYPE_SUNMI_K1("sunmiK1", SunmiK1Printer.class.getName()),
        TYPE_YINGTAI("yingtai", YingtaiPrinter.class.getName()),
        TYPE_CHUANGJIE("chuangjie", ChuangjiePrinter.class.getName()),
        TYPE_SANGDA("sangda", SangdaPrinter.class.getName());


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

        /**
         * 设备驱动类全类名
         */
        public 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;

    /**
     * 内部持有调用者初始化的应用
     */
    Context ctx;

    /**
     * 轮询初始化
     *
     * @return 是否初始化成功
     */
    public boolean init(Context context) {
        this.ctx = context;
        for (Type type : Type.values()) {
            try {
                if (printer != null) {
                    try {
                        printer.release();
                    } catch (Exception ex) {
                        //出现异常也继续进行轮询
                    }
                }
                Class printerCls = Class.forName(type.clsName);
                printer = (IPrinter) printerCls.newInstance();
                printer.setPrinterName(type.typeName);
                PrintLogger.writeLog(this.ctx, "开始初始化打印机：" + type.typeName);
                boolean result = printer.init(context);
                if (result == true) {
                    printer.setPrinterName(type.typeName);
                    PrintLogger.i(TAG, "初始化打印机成功，打印机器为：" + type.typeName);
                    PrintLogger.writeLog(this.ctx, "初始化打印机成功，打印机器为：" + type.typeName);
                    return true;
                } else {
                    PrintLogger.writeLog(this.ctx, "初始化" + type.typeName + "失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                printer = null;
                PrintLogger.writeLog(ctx, "初始化" + type.typeName + "打印机出现异常：" + e.getMessage());
            }
        }
        //没有找到对应的打印机
        if (printer != null) {
            try {
                printer.release();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            printer = null;
        }
        PrintLogger.i(TAG, "没找到对应的打印机器，请检查");
        PrintLogger.writeLog(ctx, "没找到对应的打印机器，请检查");
        return false;
    }

    /**
     * 销毁相关资源
     *
     * @return
     */
    public boolean release() {
        if (isConnected()) {
            try {
                boolean result = printer.release();
                if (result == false) {
                    return false;
                }
                printer = null;
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 保险起见提供指定硬件的初始化
     * ps:谨慎调用
     *
     * @param context
     * @param type    指定硬件类型
     * @return
     */
    public boolean init(Context context, Type type) {
        this.ctx = context;
        if (type == null) {
            return false;
        }
        //是否支持指定硬件
        boolean isSupported = false;
        for (Type tmpType : Type.values()) {
            if (type.typeName.equals(tmpType.typeName)) {
                isSupported = true;
            }
        }
        if (isSupported == false) {
            return false;
        }
        //反射新建实例
        try {
            Class printerCls = Class.forName(type.clsName);
            printer = (IPrinter) printerCls.newInstance();
            printer.setPrinterName(type.typeName);
            PrintLogger.writeLog(this.ctx, "开始初始化打印机：" + type.typeName);
            boolean result = printer.init(context);
            if (result == true) {
                printer.setPrinterName(type.typeName);
                PrintLogger.i(TAG, "初始化打印机成功，打印机器为：" + type.typeName);
            } else {
                printer = null;
                PrintLogger.writeLog(ctx, "没找到指定的打印机器:" + type.typeName + ",请检查");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            printer = null;
            PrintLogger.writeLog(ctx, "初始化" + type.typeName + "打印机出现异常：" + e.getMessage());
        }
        return false;
    }

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

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

    /**
     * 自带初始化重试的检测逻辑
     *
     * @return 如果printer！=null则返回true，否则内部初始化一次再返回初始化结果
     */
    public boolean checkIsConnectedWithRetry() {
        if (printer != null) {
            return true;
        } else if (ctx != null) {
            return init(ctx);
        }
        return false;
    }
}
