package co.dc.aptiv.mina;

import co.dc.aptiv.AptivApp;
import co.dc.commons.utils.DateTimeUtil;
import co.dc.aptiv.service.BillService;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 一道采集逻辑处理类
 *
 * @author mx
 */
public class CollectorMinaHandler extends MinaAbstractHandler {


    private static final Log log = LogFactory.getLog(CollectorMinaHandler.class);

    public CollectorMinaHandler(CollectorMina collectorMina, QueryRunner queryRunner) {
        super(collectorMina, queryRunner);
    }

    private BillService billService;


    public CollectorMinaHandler(MinaAbstract mina, QueryRunner queryRunner, BillService billService) {
        super(mina, queryRunner);
        this.billService = billService;
    }


    /**
     * 处理收到的信息
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        String data = (String) message;
        log.info("collector received [" + data + "]");
        if (data != null) {
			/*说明是网址
			data = AptivApp.httpStr(data);*/
            String str = replaceBlank(data).trim();
            if (!"ERROR".equals(str)) {
                //检查重码
                boolean RcFlag = AptivApp.qrcodeService.checkReCode(str);
                if (RcFlag) {
                    if (AptivApp.scanStatus == true) {
                        AptivApp.qrcodeService.receiveQrCode(str);
                        log.info(DateTimeUtil.getDateTimeString() + " 采集器成功采集到码：" + data);
                    }
                    AptivApp.collectorMina.getScanFrame().changeLight(AptivApp.collectorMina.getScanFrame().label_scan2, true);
                }
            }
        }
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\t|\r|\n");
            /* Pattern p = Pattern.compile("\\s*|\t|\r|\n");*/
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
}
