package com.njcn.csdevice.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.csdevice.mapper.MqttUserMapper;
import com.njcn.csdevice.pojo.po.MqttUser;
import com.njcn.csdevice.service.IMqttUserService;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuyang
 * @since 2023-06-29
 */
@Service
@DS("mqtt")
public class MqttUserServiceImpl extends ServiceImpl<MqttUserMapper, MqttUser> implements IMqttUserService {

    @Override
    public boolean findMqttUser(String userName) {
        MqttUser mqttUser = this.lambdaQuery().eq(MqttUser::getUsername,userName).one();
        return Objects.isNull(mqttUser);
    }

    @Override
    public void insertMqttUser(String password) {
        Random r = new Random();
        MqttUser mqttUser = new MqttUser();
        mqttUser.setId(1000000000 + (int)(r.nextDouble() * 999999999));
        mqttUser.setUsername(password);
        mqttUser.setSalt("mqtt");
        mqttUser.setIsSuperuser(1);
        mqttUser.setPassword(DigestUtil.sha256Hex(password + mqttUser.getSalt()));
        this.save(mqttUser);
    }

    @Override
    public void deleteUser(String ndid) {
        QueryWrapper<MqttUser>  queryWrap = new QueryWrapper<>();
        queryWrap.eq("username",ndid);
      this.getBaseMapper().delete(queryWrap);
    }


}
