package com.brframework.commonapppush.service.impl;

import com.brframework.commonapppush.dao.PushClientInfoDao;
import com.brframework.commonapppush.entity.PushClientInfo;
import com.brframework.commonapppush.service.PushClientInfoService;
import com.brframework.commondb.core.AbstractEntityService;
import com.brframework.commondb.core.CommonRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;

/**
 * 客户端信息
 * @author xu
 * @date 2019/11/18 19:22
 */
@Service
@Slf4j
public class PushClientInfoServiceImpl extends AbstractEntityService<PushClientInfo, Long, Object>
        implements PushClientInfoService {

    @Autowired
    PushClientInfoDao pushClientInfoDao;

    @Override
    public CommonRepository<Long, PushClientInfo> getRepository() {
        return pushClientInfoDao;
    }

    @Override
    @Transactional
    public void binding(String userTokens, String deviceTokens) {
        if(StringUtils.isEmpty(userTokens)){
            log.error("userTokens为空，无法进行绑定");
            return;
        }
        if(StringUtils.isEmpty(deviceTokens)){
            log.error("deviceTokens为空，无法进行绑定");
            return;
        }

        PushClientInfo byDeviceTokens = findByDeviceTokens(deviceTokens);
        if(byDeviceTokens != null){
            if(byDeviceTokens.getUserTokens().equals(userTokens)){
                log.info("用户userTokens：{}已经绑定，无需重复绑定", userTokens);
                return;
            }

            unbindingByDeviceTokens(deviceTokens);
        }

        if(findByUserTokens(userTokens) != null){
            unbindingByUserTokens(userTokens);
        }

        PushClientInfo info = new PushClientInfo();
        info.setCreateDate(LocalDateTime.now());


        info.setUserTokens(userTokens);
        info.setDeviceTokens(deviceTokens);
        pushClientInfoDao.save(info);
    }

    @Override
    public void unbindingByUserTokens(String userTokens) {
        pushClientInfoDao.deleteByUserTokens(userTokens);
    }

    @Override
    public void unbindingByDeviceTokens(String deviceTokens) {
        pushClientInfoDao.deleteByDeviceTokens(deviceTokens);
    }

    @Override
    public PushClientInfo findByUserTokens(String userTokens) {
        return pushClientInfoDao.findByUserTokens(userTokens);
    }

    @Override
    public PushClientInfo findByDeviceTokens(String deviceTokens) {
        return pushClientInfoDao.findByDeviceTokens(deviceTokens);
    }
}
