package com.sjyt.icom.asst.context.pools;

import com.sjyt.icom.asst.common.model.room.OneToOneRoom;
import com.sjyt.icom.asst.common.enums.RoomEnum;
import com.sjyt.icom.asst.common.util.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * <p>One2OneRoom 工厂类</p>
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/6/16 11:00
 */
@Slf4j
public class One2OneRoomFactory implements PooledObjectFactory<OneToOneRoom> {
    /**
     * 激活对象，使其可用
     *
     * @param pooledObject p
     * @throws Exception e
     */
    @Override
    public void activateObject(PooledObject<OneToOneRoom> pooledObject) throws Exception {
        OneToOneRoom object = pooledObject.getObject();
        object.setRid(String.valueOf(IdUtils.snowflake()));
        object.setActive(true);
    }

    /**
     * 销毁对象
     *
     * @param pooledObject p
     * @throws Exception e
     */
    @Override
    public void destroyObject(PooledObject<OneToOneRoom> pooledObject) throws Exception {
        OneToOneRoom object = pooledObject.getObject();
        object.destroy();
    }

    /**
     * 构建对象
     *
     * @return r
     * @throws Exception e
     */
    @Override
    public PooledObject<OneToOneRoom> makeObject() throws Exception {
        OneToOneRoom object = new OneToOneRoom();
        log.info("构建一对一房间对象,房间类型为：{}", RoomEnum.of(object.getType()));
        return new DefaultPooledObject<>(object);
    }

    /**
     * 钝化对象
     *
     * @param pooledObject p
     * @throws Exception e
     */
    @Override
    public void passivateObject(PooledObject<OneToOneRoom> pooledObject) throws Exception {
        OneToOneRoom object = pooledObject.getObject();
        object.setRid(null);
        object.getExtraInfos().clear();
    }

    /**
     * 验证对象是否可用
     *
     * @param pooledObject p
     * @return r
     */
    @Override
    public boolean validateObject(PooledObject<OneToOneRoom> pooledObject) {
        OneToOneRoom object = pooledObject.getObject();
        return object.isActive();
    }
}
