import {Injectable} from '@nestjs/common';
import {CreateUserDto} from './dto/create-user.dto';
import {UpdateUserDto} from './dto/update-user.dto';
import {InjectRepository} from "@nestjs/typeorm";
import {User} from "./entities/user.entity";
import {Repository} from "typeorm";
import {makePersonEntry} from "../utils/ldap";

@Injectable()
export class UserService {
    constructor(@InjectRepository(User) private userRepository: Repository<User>) {
    }

    create(createUserDto: CreateUserDto) {
        return 'This action adds a new user';
    }

    findAll() {
        return `This action returns all user`;
    }

    findOne(cn: string) {
        return this.userRepository.findOneBy({name: cn});
    }

    async fetchAllUserEntries() {
        const users = await this.userRepository.find();
        const entries = [];
        for (let user of users) {
            const dn = `cn=${user.name}`;
            // const dn = `mail=${mail},${u.firstDepartment.dn}`;
            // 映射到 iNetOrgPerson
            const personEntry = makePersonEntry(dn, {
                uid: user.name,
                title: "",
                mobileTelephoneNumber: "",
                cn: user.name,
                givenName: "",
                sn: "",
                mail: "",
                avatarurl: "",
                userPassword: user.password,
            });

            entries.push(personEntry);

        }
        return entries;
    }

    update(id: number, updateUserDto: UpdateUserDto) {
        return `This action updates a #${id} user`;
    }

    remove(id: number) {
        return `This action removes a #${id} user`;
    }
}
