package wtf.socket.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wtf.socket.WTFSocketServer;
import wtf.socket.protocol.WTFSocketMsg;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 调试信息辅助日志工具类
 * <p>
 * Created by ZFly on 2017/4/21.
 */
public final class WTFSocketLogUtils {

    private WTFSocketLogUtils() {
    }

    private static final Log logger = LogFactory.getLog(WTFSocketLogUtils.class);

    public static void received(WTFSocketServer context, String packet, WTFSocketMsg msg) {
        final String receiveMsg = String.format(
                "Received[%s] message from [%s] to [%s]:\n%s\n",
                msg.getConnectType(),
                msg.getFrom(),
                msg.getTo(),
                packet);
        if (!context.getRouting().getDebugMap().contains(msg.getFrom())) {
            debugOutput(context, receiveMsg, 1);
        }
    }

    public static void forwarded(WTFSocketServer context, String packet, WTFSocketMsg msg) {
        final String dispatchMsg = String.format(
                "Forwarded[%s] message from [%s] to [%s]:\n%s\n",
                msg.getConnectType(),
                msg.getFrom(),
                msg.getTo(),
                packet);
        if (!context.getRouting().getDebugMap().contains(msg.getTo())) {
            debugOutput(context, dispatchMsg, 1);
        }
    }

    public static void exception(WTFSocketServer context, String packet, WTFSocketMsg msg) {
        final String exceptionMsg = String.format(
                "Exception[%s] on [%s]:\n%s\n",
                msg.getConnectType(),
                msg.getTo(),
                packet);
        if (!context.getRouting().getDebugMap().contains(msg.getTo())) {
            debugOutput(context, exceptionMsg, 2);
        }
    }

    private static void debugOutput(WTFSocketServer context, String msg, int level) {
        final DateFormat format = new SimpleDateFormat("hh:mm:ss,SSS");
        final String date = format.format(new Date());
        if (level == 1)
            logger.info(msg);
        context.getRouting().getDebugMap().values().stream()
                .filter(item -> item.isFilter(msg))
                .forEach(item -> {
                    item.getTerm().write(String.format("[%s] %s - %s", item.getAddress(), date, msg));
                });
    }
}

@@ -943,19 +943,16 @@
 ceiveMsg
-, 1
 );%0A     
@@ -1416,11 +1416,8 @@
 hMsg
-, 1
 );%0A 
@@ -1838,11 +1838,8 @@
 nMsg
-, 2
 );%0A 
@@ -1929,19 +1929,8 @@
  msg
-, int level
 ) %7B%0A
@@ -2060,36 +2060,8 @@
 ));%0A
-        if (level == 1)%0A    
     
@@ -2076,19 +2076,20 @@
 er.info(
-msg
+date
 );%0A     
@@ -2232,30 +2232,8 @@
 m -%3E
- %7B%0A                   
  ite
@@ -2314,27 +2314,8 @@
 sg))
-;%0A                %7D
 );%0A 

fix bug