package com.webchat.service.behavior;

import com.webchat.common.exception.BusinessException;
import com.webchat.common.util.SpringContextUtil;
import com.webchat.repository.dao.IResourceBehaviorDAO;
import com.webchat.repository.entity.ResourceBehaviorEntity;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

/**
 * 资源行为服务 - 写 (双向：包含取消行为)
 */
public class ResourceTwoWayBehaviorService extends AbstractResourceBehaviorService {

    @Override
    public boolean behaviorResource(String userId, Long resourceIndex, String resourceType, String behaviorType) {
        IResourceBehaviorDAO resourceBehaviorDAO = SpringContextUtil.getBean(IResourceBehaviorDAO.class);
        List<ResourceBehaviorEntity> behaviorEntityList =
                resourceBehaviorDAO.findAllByUserIdAndResourceIndexAndResourceTypeAndBehaviorType(
                        userId, resourceIndex, resourceType, behaviorType);
        ResourceBehaviorEntity behaviorEntity;
        if (CollectionUtils.isNotEmpty(behaviorEntityList)) {
            behaviorEntity = behaviorEntityList.get(0);
            if (behaviorEntity.getStatus()) {
                return true;
            }
        } else {
            behaviorEntity = new ResourceBehaviorEntity();
            behaviorEntity.setUserId(userId);
            behaviorEntity.setResourceIndex(resourceIndex);
            behaviorEntity.setResourceType(resourceType);
            behaviorEntity.setBehaviorType(behaviorType);
        }
        behaviorEntity.setStatus(Boolean.TRUE);
        resourceBehaviorDAO.save(behaviorEntity);
        return true;
    }

    @Override
    public boolean cancelBehaviorResource(String userId, Long resourceIndex, String resourceType, String behaviorType) {
        IResourceBehaviorDAO resourceBehaviorDAO = SpringContextUtil.getBean(IResourceBehaviorDAO.class);
        List<ResourceBehaviorEntity> behaviorEntityList =
                resourceBehaviorDAO.findAllByUserIdAndResourceIndexAndResourceTypeAndBehaviorType(
                        userId, resourceIndex, resourceType, behaviorType);
        ResourceBehaviorEntity behaviorEntity;
        if (CollectionUtils.isNotEmpty(behaviorEntityList)) {
            behaviorEntity = behaviorEntityList.get(0);
            if (behaviorEntity.getStatus()) {
                behaviorEntity.setStatus(false);
            }
        } else {
            throw new BusinessException("不能重复操作");
        }
        resourceBehaviorDAO.save(behaviorEntity);
        return true;
    }
}
