package co.dc.aptiv.mina;


import co.dc.aptiv.ScanFrame;
import co.dc.aptiv.service.BillService;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;


@Service("collectorMina")
public class CollectorMina extends MinaAbstract {

    private static final Log log = LogFactory.getLog(CollectorMina.class);
    @Resource
    private QueryRunner queryRunner;
    @Resource
    private BillService billService;
    @Resource
    private Configuration configuration;

    private ScanFrame scanFrame;

    @Override
    public void init(boolean init) {
        // 创建网口连接客户端
        connector = new NioSocketConnector();

        connector.getFilterChain().addLast("log", new LoggingFilter());
        //	connector.getFilterChain().addLast("codec",
        //	new ProtocolCodecFilter(new MessageCodecFactory(true,true)));
        //发送时用字符串，结束字符用空格，接收时以\r 分割字符串 进行粘包和拆包
        // 传送对象
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.defaultCharset(), LineDelimiter.MAC, LineDelimiter.MAC)));
        // 读写都空闲时间:30秒
        connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
        //connector.getSessionConfig().setReadBufferSize(1024 * 1024);// 发送缓冲区1M
        //((NioSocketConnector)connector).getSessionConfig().setReceiveBufferSize(1024 * 1024);// 接收缓冲区1M
        // 设置连接超时检查时间
        connector.setConnectTimeoutCheckInterval(30);
        // 添加处理器
        connector.setHandler(new CollectorMinaHandler(this, queryRunner, billService));
        setIp(configuration.getString("machine.ip"));
        setPort(configuration.getInt("machine.port"));
        connector.setDefaultRemoteAddress(new InetSocketAddress(getIp(), getPort()));
        if (init == true) {
            if (createConn()) {

            }
        }

    }


    public ScanFrame getScanFrame() {
        return scanFrame;
    }

    public void setScanFrame(ScanFrame scanFrame) {
        this.scanFrame = scanFrame;
    }
}
