package org.springblade.common.notify.rocketmq.producer;

import com.aliyun.openservices.ons.api.PropertyKeyConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.io.Serializable;
import java.util.Properties;

/**
 * 对象池工厂
 *
 * @author caiyihua
 */
@Slf4j
public class ProducerProxyPooledObjectFactory implements PooledObjectFactory<ProducerProxy>, Serializable {
    Properties properties;

    public ProducerProxyPooledObjectFactory(Properties properties) {
        this.properties = properties;
    }

    @Override
    public PooledObject<ProducerProxy> makeObject() throws Exception {
        ProducerProxy producerProxy = ProducerProxyFactory.makeProducerProxy(properties.getProperty(PropertyKeyConst.MQType));
        producerProxy.startup(properties);
        log.info("Producer proxy has been started! Producer proxy: {}", producerProxy);
        return new DefaultPooledObject(producerProxy);
    }

    @Override
    public void destroyObject(PooledObject<ProducerProxy> p) throws Exception {
        ProducerProxy o = p.getObject();
        o.shutdown();
        log.info("Producer proxy has been shutdown! Producer proxy: {}", o);
        o = null;
    }

    @Override
    public boolean validateObject(PooledObject<ProducerProxy> p) {
        ProducerProxy o = p.getObject();
        return o.isStarted();
    }

    @Override
    public void activateObject(PooledObject<ProducerProxy> p) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<ProducerProxy> p) throws Exception {

    }
}
