package service;

import dao.DAOFactory;
import dao.TeacherDAO;
import model.Teacher;
import java.util.List;

/**
 * 教师信息服务类
 */
public class TeacherService {
    private final TeacherDAO teacherDAO = DAOFactory.getTeacherDAO();

    /**
     * 更新教师信息
     * @param teacher 教师信息
     * @return 是否更新成功
     */
    public boolean updateTeacher(Teacher teacher) {
        // 检查是否存在
        Teacher existingTeacher = teacherDAO.findById(teacher.getId());
        if (existingTeacher == null) {
            return false;
        }
        // 检查工号是否被其他教师使用
        Teacher teacherWithSameId = teacherDAO.findByTeacherId(teacher.getTeacherId());
        if (teacherWithSameId != null && teacherWithSameId.getId() != teacher.getId()) {
            return false;
        }
        return teacherDAO.update(teacher) > 0;
    }

    /**
     * 根据ID查询教师
     * @param id 教师ID
     * @return 教师信息
     */
    public Teacher getTeacherById(int id) {
        return teacherDAO.findById(id);
    }

    /**
     * 根据工号查询教师
     * @param teacherId 工号
     * @return 教师信息
     */
    public Teacher getTeacherByTeacherId(String teacherId) {
        return teacherDAO.findByTeacherId(teacherId);
    }

    /**
     * 查询所有教师
     * @return 教师列表
     */
    public List<Teacher> getAllTeachers() {
        return teacherDAO.findAll();
    }

    /**
     * 教师登录
     * @param teacherId 教师工号
     * @param password 密码
     * @return 登录成功返回教师信息，失败返回null
     */
    public Teacher login(String teacherId, String password) {
        Teacher teacher = teacherDAO.findByTeacherId(teacherId);
        System.out.println("Login attempt - TeacherID: " + teacherId);
        System.out.println("Teacher found: " + (teacher != null));
        if (teacher != null) {
            System.out.println("Stored password: " + teacher.getPassword());
            System.out.println("Input password: " + password);
            System.out.println("Password match: " + password.equals(teacher.getPassword()));
        }
        if (teacher != null && password.equals(teacher.getPassword())) {
            return teacher;
        }
        return null;
    }
}
