package com.gingersoft.gsa.cloud.common.core.print.newprint;

import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.print.PrintSocketHolder;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ConnectPrintUtil {
    /**
     * volatile关键字： 保持内存的可见性--所有线程都能获取的共享内存的最新状态
     * volatile的作用：每次读取前必须先从主存刷新最新的值，每次写入后必须立即同步回主存当中
     */
    private static volatile ConnectPrintUtil connectPrintUtil;

    private ConnectPrintUtil() {
    }

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

    private Map<String, Socket> socketMap = new HashMap<>();

    private PrintStatesChangeListener mPrintStatesChangeListener;

    private PrintMessageBean printMessageBean;

    public ConnectPrintUtil setPrintStatesChangeListener(PrintStatesChangeListener printStatesChangeListener) {
        mPrintStatesChangeListener = printStatesChangeListener;
        return connectPrintUtil;
    }

    public ConnectPrintUtil connect(String ip) {
        return connect(ip, 9100);
    }

    public ConnectPrintUtil connect(String ip, int port) {
        setState(PrintSocketHolder.STATE_1, "");
        Socket socket = socketMap.get(ip);
        if (socket != null && socket.isConnected()) {
            setState(PrintSocketHolder.STATE_1, "");
        } else {
            socket = new Socket();//ip, port
            InetSocketAddress socketAddress = new InetSocketAddress(ip, port);
            //设置 超时时间
            try {
                socket.setSoTimeout(PrintConstans.SO_TIMEOUT);
                socket.connect(socketAddress, PrintConstans.PRINT_TIMEOUT);//开始连接ip
                socketMap.put(ip, socket);
            } catch (IOException e) {
                socketMap.remove(ip);
                setState(PrintSocketHolder.ERROR_1, "連接失敗" + e.getMessage());
                e.printStackTrace();
            }
        }
        return connectPrintUtil;
    }

    private void setState(int code, String msg) {
        if (mPrintStatesChangeListener != null) {
            if (printMessageBean == null) {
                printMessageBean = new PrintMessageBean(code, msg);
            }
            mPrintStatesChangeListener.onStateChange(printMessageBean);
        }
    }
}
