package model;

public class User {
    private final String email;
    private final String username; // 新增字段
    private String hashedPassword;
    private UserType userType;

    public User(String email, String username, String hashedPassword, UserType userType) {
        this.email = email;
        this.username = username;
        this.hashedPassword = hashedPassword;
        this.userType = userType;
    }

    public String getEmail() { return email; }
    public String getUsername() { return username; } // 新增Getter
    public String getHashedPassword() { return hashedPassword; }
    public UserType getUserType() { return userType; }
    public void setUserType(UserType userType) { this.userType = userType; }

    public void setHashedPassword(String plainPassword) {
        this.hashedPassword = Integer.toString(plainPassword.hashCode());
    }

    private void setHashedPasswordDirectly(String hashedPassword) {
        this.hashedPassword = hashedPassword;
    }

    @Override
    public String toString() {
        // 新的4字段格式，用户名可以为空字符串
        return String.join("|", email, username == null ? "" : username, hashedPassword, userType.name());
    }


    public static User fromString(String line) {
        String[] parts = line.split("\\|");
        User user = null;
        if (parts.length == 4) { // 新格式: email|username|password|type
            String email = parts[0];
            String username = parts[1].isEmpty() ? null : parts[1];
            String password = parts[2];
            UserType type = UserType.valueOf(parts[3]);
            user = new User(email, username, "", type);
            user.setHashedPasswordDirectly(password);
        } else if (parts.length == 3) { // 旧格式: email|password|type
            String email = parts[0];
            String password = parts[1];
            UserType type = UserType.valueOf(parts[2]);
            user = new User(email, null, "", type); // 旧用户没有用户名
            user.setHashedPasswordDirectly(password);
        }
        return user;
    }
}