ГОВОРИ НА РУССКОМ. Я работаю с таким вот текстовым файлом 

<users>
id:12; name:Bobis; password:2212qwrqwe@; role:student; group:Group3; 
id:3; name:Nasd; password:22; role:admin; 
id:111; name: admin; password: admin; role:admin; 
id:101; name: Teacher1; password: a; role:teacher; 
id:102; name: Teacher2; password: a; role:teacher; 
id:1; name: susana22; password: a; role:student; group:Group1; 
id:3; name: a33; password: a; role:student; group:Group1; 
id:4; name: John Doe; password: a; role:student; group:Group2; 
id:5; name: Alice Smith; password: a; role:student; group:Group2; 
id:6; name: Michael Johnson; password: a; role:student; group:Group2; 
</users>

<teachers>
<teacher: Teacher1>
Teacher1
/g
Group1
Math
Physics
/g
Group2
Biology
Chemistry
/    
</teacher: Teacher1>
<teacher: Teacher2>
Teacher2
/g
Group1
IT
Sport
/g
Group2
Memology
/
</teacher: Teacher2>
</teachers>

<List> Groups: Group1, Group2,

<groups>
<Group: Group1>
Group1:
1; susana22
2; Борисова Виктория Андреевна
3; a 
</Group: Group1>
<Group: Group2>
Group2:
4; John Doe
5; Alice Smith
6; Michael Johnson
</Group: Group2>
<Group: Group3>
Group3:
7; Emma Brown
8; Alexander White
9; Sophia Lee
</Group: Group3>
</groups>

<Group: Group1;Teacher: Teacher1;Subject: Math;>

<Lesson: year:2019, month:December>

<Day: 1>
1; susana22; Present; 8
2; Борисова Виктория Андреевна; Absent; 10
3; a; Present; 7
</Day: 1>
<Day: 5>
1; susana22; Present; 5
2; Борисова Виктория Андреевна; Present; 0
3; a; Present; 7
</Day: 5>
<Day: 7>
1; susana22; Present; 5
2; Борисова Виктория Андреевна; Present; 3
3; a; Present; 1
</Day: 7>
</Lesson: year:2019, month:December>

</Group: Group1;Teacher: Teacher1;Subject: Math;>

<Group: Group2;Teacher: Teacher1;Subject: Biology;>

<Lesson: year:2019, month:December>

<Day: 1>
1; susana22; Present; 8
2; Борисова Виктория Андреевна; Absent; 10
3; a; Present; 7
</Day: 1>
<Day: 5>
1; susana22; Present; 5
2; Борисова Виктория Андреевна; Present; 0
3; a; Present; 7
</Day: 5>
<Day: 7>
1; susana22; Present; 5
2; Борисова Виктория Андреевна; Present; 3
3; a; Present; 1
</Day: 7>
</Lesson: year:2019, month:December>

</Group: Group2;Teacher: Teacher1;Subject: Biology;>

<Group: Group2;Teacher: Teacher1;Subject: Chemistry;>

<Lesson: year:2019, month:December>

<Day: 1>
1; susana22; Present; 8
2; Борисова Виктория Андреевна; Absent; 10
3; a; Present; 7
</Day: 1>
<Day: 5>
1; susana22; Present; 5
2; Борисова Виктория Андреевна; Present; 0
3; a; Present; 7
</Day: 5>
<Day: 7>
1; susana22; Present; 5
2; Борисова Виктория Андреевна; Present; 3
3; a; Present; 1
</Day: 7>
</Lesson: year:2019, month:December>

</Group: Group2;Teacher: Teacher1;Subject: Chemistry;>


<Group: Group1;Teacher: Teacher1;Subject: Physics;>
<Lesson: year:2020, month:June>
</Lesson: year:2020, month:June>
</Group: Group1;Teacher: Teacher1;Subject: Physics;>

<Group: Group2;Teacher: Teacher2;Subject: Memology;>
<Lesson: year:2020, month:January>
<Day: 1>
4; John Doe; Present; 10
5; Alice Smith; Absent; 5
6; Michael Johnson; Absent; 0
</Day: 1>
<Day: 5>
4; John Doe; Absent; 0
5; Alice Smith; Present; 3
6; Michael Johnson; Absent; 0
</Day: 5>
</Lesson: year:2020, month:January>
</Group: Group2;Teacher: Teacher2;Subject: Memology;>


Я хочу, чтобы при работе сохранялся текущий расклад синтаксиса. То есть все там такие моменты с расстановкой запятой, или пробелами или чем-то таким 

package Model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class DataAnalyzer2 {
	
    private static final String FILE_PATH = "E:\\JavaProjects\\Journal\\src\\main\\webapp\\data\\data.txt";
    
    private static Map<String, User> users = new HashMap<>();

    public DataAnalyzer2() {
        loadData();
    }

    private void loadData() {
        boolean inUsersBlock = false;
        try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().equals("<users>")) {
                    inUsersBlock = true;
                } else if (line.trim().equals("</users>")) {
                    inUsersBlock = false;
                } else if (inUsersBlock && line.startsWith("id:")) {
                    String[] parts = line.split("; ");
                    String id = parts[0].split(":")[1].trim();
                    String name = parts[1].split(":")[1].trim();
                    String password = parts[2].split(":")[1].trim();
                    String role = parts[3].split(":")[1].trim();
                    String group = parts.length > 4 ? parts[4].split(":")[1].trim() : null;
                    users.put(name, new User(id, name, password, role, group));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static User authenticate(String username, String password) {
        User user = users.get(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }
    
    public static List<String> readFile() throws IOException {
        List<String> lines = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        reader.close();
        return lines;
    }

    public static List<String> findTeacherGroups(String teacherName) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get(FILE_PATH)), StandardCharsets.UTF_8);
        List<String> groups = new ArrayList<>();

        // Regular expression to match the teacher block
        Pattern teacherPattern = Pattern.compile("<teacher: " + teacherName + ">(.*?)</teacher: " + teacherName + ">", Pattern.DOTALL);
        Matcher teacherMatcher = teacherPattern.matcher(content);

        if (teacherMatcher.find()) {
            // Get the block of text corresponding to the teacher
            String teacherBlock = teacherMatcher.group(1);

            // Regular expression to find groups within the teacher block
            Pattern groupPattern = Pattern.compile("/g\\s*(\\w+)");
            Matcher groupMatcher = groupPattern.matcher(teacherBlock);

            while (groupMatcher.find()) {
                // Extract group names
                String groupName = groupMatcher.group(1).trim();
                groups.add(groupName);
            }
        }
        return groups;
    }

    public boolean deleteLesson(String groupName, String teacherName, String subjectName, String year, String month) {
        List<String> lines;
        try {
            lines = Files.readAllLines(Paths.get(FILE_PATH));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        
        System.out.println(groupName + teacherName + subjectName + year+ month);
        boolean inGroup = false, inLesson = false;
        String lessonStartTag = "<Lesson: year:" + year + ", month:" + month + ">";
        String lessonEndTag = "</Lesson: year:" + year + ", month:" + month + ">";

        List<String> newLines = new ArrayList<>();
        for (String line : lines) {
            if (line.startsWith("<Group:") && line.contains("Group: " + groupName) && line.contains("Teacher: " + teacherName) && line.contains("Subject: " + subjectName + ";>")) {
                inGroup = true;
            } else if (line.startsWith("<Group:")) {
                inGroup = false;
            }

            if (inGroup && line.equals(lessonStartTag)) {
                inLesson = true;
                continue; // Skip the lesson start tag
            }

            if (inLesson && line.equals(lessonEndTag)) {
                inLesson = false;
                continue; // Skip the lesson end tag
            }

            if (!inLesson) {
                newLines.add(line);
            }
        }

        try {
            Files.write(Paths.get(FILE_PATH), newLines);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }




    public static List<String> findGroupSubjects(String groupName, String teacherName) throws IOException {
        List<String> lines = readFile();
        List<String> subjects = new ArrayList<>();
        Pattern pattern = Pattern.compile("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: (.*?);>");
        
        for (String line : lines) {
            Matcher matcher = pattern.matcher(line);
            if (matcher.find()) {
                subjects.add(matcher.group(1));
            }
        }
        return subjects;
    }

    public static Set<String> findAvailableYears(String groupName, String subjectName) throws IOException {
        List<String> lines = readFile();
        Set<String> years = new HashSet<>();
        Pattern lessonPattern = Pattern.compile("<Group: " + groupName + ";Teacher: .*?;Subject: " + subjectName + ";>");
        Pattern yearPattern = Pattern.compile("<Lesson: year:(\\d+), month:.*>");

        boolean inCorrectSubject = false;

        for (String line : lines) {
            if (lessonPattern.matcher(line).find()) {
                inCorrectSubject = true;
                continue;
            }

            if (inCorrectSubject) {
                Matcher yearMatcher = yearPattern.matcher(line);
                if (yearMatcher.find()) {
                    years.add(yearMatcher.group(1));
                }

                if (line.matches("</Group: " + groupName + ";Teacher: .*?;Subject: " + subjectName + ";>")) {
                    inCorrectSubject = false;
                }
            }
        }

        return years;
    }

    public static Set<String> findAvailableMonths(String groupName, String subjectName, String year) throws IOException {
        List<String> lines = readFile();
        Set<String> months = new HashSet<>();
        Pattern lessonPattern = Pattern.compile("<Group: " + groupName + ";Teacher: .*?;Subject: " + subjectName + ";>");
        Pattern monthPattern = Pattern.compile("<Lesson: year:" + year + ", month:(.*)>");

        boolean inCorrectSubject = false;

        for (String line : lines) {
            if (lessonPattern.matcher(line).find()) {
                inCorrectSubject = true;
                continue;
            }

            if (inCorrectSubject) {
                Matcher monthMatcher = monthPattern.matcher(line);
                if (monthMatcher.find()) {
                    months.add(monthMatcher.group(1));
                }

                if (line.matches("</Group: " + groupName + ";Teacher: .*?;Subject: " + subjectName + ";>")) {
                    inCorrectSubject = false;
                }
            }
        }

        return months;
    }


    public static List<GradeEntry> findStudentGrades(String groupName, String studentName, String subjectName, String year, String month) throws IOException {
        List<String> lines = readFile();
        List<GradeEntry> grades = new ArrayList<>();
        Pattern lessonPattern = Pattern.compile("<Group: " + groupName + ";Teacher: .*?;Subject: " + subjectName + ";>");
        Pattern yearMonthPattern = Pattern.compile("<Lesson: year:" + year + ", month:" + month + ">");
        Pattern dayPattern = Pattern.compile("<Day: (\\d+)>");
        Pattern studentPattern = Pattern.compile("(\\d+); " + studentName + "; (Present|Absent); (\\d+)");

        boolean inCorrectLesson = false;
        boolean inCorrectDay = false;
        String currentDay = null;

        for (String line : lines) {
            if (lessonPattern.matcher(line).find()) {
                inCorrectLesson = true;
                continue;
            }

            if (inCorrectLesson && yearMonthPattern.matcher(line).find()) {
                inCorrectDay = true;
                continue;
            }

            if (inCorrectLesson && inCorrectDay) {
                Matcher dayMatcher = dayPattern.matcher(line);
                if (dayMatcher.find()) {
                    currentDay = dayMatcher.group(1);
                    continue;
                }

                Matcher studentMatcher = studentPattern.matcher(line);
                if (studentMatcher.find()) {
                    String studentId = studentMatcher.group(1);
                    boolean presence = studentMatcher.group(2).equalsIgnoreCase("Present");
                    int grade = Integer.parseInt(studentMatcher.group(3));
                    grades.add(new GradeEntry(currentDay, studentId, studentName, presence, grade));
                }

                if (line.matches("</Lesson: year:" + year + ", month:" + month + ">")) {
                    inCorrectDay = false;
                }
            }

            if (line.matches("</Group: " + groupName + ";Teacher: .*?;Subject: " + subjectName + ";>")) {
                inCorrectLesson = false;
            }
        }

        return grades;
    }


    public static boolean deleteSubject(String groupName, String teacherName, String subjectName) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(FILE_PATH));
        List<String> updatedLines = new ArrayList<>();
        boolean subjectFoundInGroup = false;
        boolean subjectFoundInTeacher = false;
        System.out.println(groupName + teacherName + subjectName);

        // Удаление из раздела <groups>
        boolean inGroupSection = false;
        for (String line : lines) {
            if (line.startsWith("<Group:") && line.contains(groupName) && line.contains(teacherName) && line.contains(subjectName)) {
                inGroupSection = true;
                subjectFoundInGroup = true;
                continue;
            }
            if (inGroupSection && line.startsWith("</Group:") && line.contains(groupName) && line.contains(teacherName) && line.contains(subjectName)) {
                inGroupSection = false;
                continue;
            }
            if (!inGroupSection) {
                updatedLines.add(line);
            }
        }

        // Обновление lines для дальнейшей обработки
        lines = new ArrayList<>(updatedLines);
        updatedLines.clear();

        // Удаление из раздела <teachers>
        boolean inTeacherSection = false;
        boolean inGroup = false;
        for (String line : lines) {
            if (line.equals("<teacher: " + teacherName + ">")) {
                inTeacherSection = true;
                updatedLines.add(line);
                continue;
            }
            if (inTeacherSection && line.startsWith("<teacher:")) {
                inTeacherSection = false;
                inGroup = false;
            }
            if (inTeacherSection && line.trim().equals("/g")) {
                inGroup = false;
            }
            if (inTeacherSection && line.trim().equals(groupName)) {
                inGroup = true;
                updatedLines.add(line);
                continue;
            }
            if (inTeacherSection && inGroup && line.trim().equals(subjectName)) {
                subjectFoundInTeacher = true;
                continue;
            }
            updatedLines.add(line);
        }

        if (!subjectFoundInGroup && !subjectFoundInTeacher) {
            System.out.println("ingroup: " + subjectFoundInGroup + " inteacher: " + subjectFoundInTeacher);
            return false; // Subject not found in both sections
        }

        // Удаление пустых строк
        List<String> finalLines = new ArrayList<>();
        for (String line : updatedLines) {
            if (!line.trim().isEmpty()) {
                finalLines.add(line);
            }
        }

        Files.write(Paths.get(FILE_PATH), finalLines, StandardCharsets.UTF_8);
        return true;
    }

    

    public void updateGroups() throws IOException {
        List<String> lines = new ArrayList<>();
        Map<String, List<String>> groupMembers = new HashMap<>();

        // Чтение файла и сохранение содержимого в список строк
        try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        }

        // Удаление текущей секции <groups>...</groups> и добавление строк в новый список
        List<String> newLines = new ArrayList<>();
        boolean inGroupsSection = false;
        for (String line : lines) {
            if (line.contains("<groups>")) {
                inGroupsSection = true;
                continue;
            }
            if (line.contains("</groups>")) {
                inGroupsSection = false;
                continue;
            }
            if (!inGroupsSection) {
                newLines.add(line);
            }
        }

        // Перебор пользователей для актуализации групп
        boolean inUsersSection = false;
        for (String line : lines) {
            if (line.contains("<users>")) {
                inUsersSection = true;
                continue;
            }
            if (line.contains("</users>")) {
                inUsersSection = false;
                continue;
            }
            if (inUsersSection) {
                if (line.contains("role:student;")) {
                    String[] attributes = line.split("; ");
                    String group = "";
                    String userName = "";
                    for (String attribute : attributes) {
                        String[] keyValue = attribute.split(":");
                        if (keyValue[0].equals("group")) {
                            group = keyValue[1].trim();
                            // Удаление последнего символа (;) если он есть
                            if (group.endsWith(";")) {
                                group = group.substring(0, group.length() - 1);
                            }
                        }
                        if (keyValue[0].equals("name")) {
                            userName = keyValue[1].trim();
                        }
                    }
                    if (!group.isEmpty()) {
                        groupMembers.putIfAbsent(group, new ArrayList<>());
                        groupMembers.get(group).add(userName);
                    }
                }
            }
        }

        // Вставка новой секции <groups> сразу после <List>
        List<String> finalLines = new ArrayList<>();
        boolean listFound = false;
        for (String line : newLines) {
            finalLines.add(line);
            if (line.contains("<List>")) {
                listFound = true;
            }
            if (listFound && !line.contains("</List>")) {
                finalLines.add("<groups>");
                for (Map.Entry<String, List<String>> entry : groupMembers.entrySet()) {
                    String group = entry.getKey();
                    finalLines.add("<Group: " + group + ">");
                    finalLines.add(group + ":");
                    for (String member : entry.getValue()) {
                        finalLines.add(member);
                    }
                    finalLines.add("</Group: " + group + ">");
                }
                finalLines.add("</groups>");
                listFound = false;  // Чтобы вставить только один раз
            }
        }

        // Запись измененного содержимого в файл
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_PATH))) {
            for (String line : finalLines) {
                bw.write(line);
                bw.newLine();
            }
        }
    }
    
    
    public static boolean addSubject(String groupName, String teacherName, String subjectName) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(FILE_PATH));
        List<String> updatedLines = new ArrayList<>();
        boolean groupFound = false;
        boolean subjectAdded = false;

        for (String line : lines) {
            updatedLines.add(line);
            if (line.contains("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>")) {
                groupFound = true;
                break;
            }
            if (line.contains("</Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>")) {
                updatedLines.add("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
                updatedLines.add("</Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
                groupFound = true;
                break;
            }
        }

        if (!groupFound) {
            updatedLines.add("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
            updatedLines.add("</Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
        }

        boolean inTeacher = false;
        boolean inGroup = false;
        for (int i = 0; i < updatedLines.size(); i++) {
            String line = updatedLines.get(i);
            if (line.equals("<teacher: " + teacherName + ">")) {
                inTeacher = true;
            } else if (inTeacher && line.startsWith("<teacher:")) {
                inTeacher = false;
            } else if (inTeacher && line.trim().equals("/g")) {
                inGroup = true;
            } else if (inGroup && line.trim().equals(groupName)) {
                int j = i + 1;
                while (j < updatedLines.size() && !updatedLines.get(j).trim().equals("/g") && !updatedLines.get(j).trim().equals("/")) {
                    j++;
                }
                updatedLines.add(j, "\t\t" + subjectName);
                subjectAdded = true;
                break;
            }
        }

        if (inTeacher && !subjectAdded) {
            for (int i = 0; i < updatedLines.size(); i++) {
                if (updatedLines.get(i).equals("<teacher: " + teacherName + ">")) {
                    int j = i + 1;
                    while (j < updatedLines.size() && !updatedLines.get(j).startsWith("<")) {
                        j++;
                    }
                    updatedLines.add(j, "\t/g");
                    updatedLines.add(j + 1, "\t" + groupName);
                    updatedLines.add(j + 2, "\t\t" + subjectName);
                    updatedLines.add(j + 3, "\t/g");
                    break;
                }
            }
        }

        Files.write(Paths.get(FILE_PATH), updatedLines, StandardCharsets.UTF_8);
        return true;
    }
    
    public boolean deleteTeacher(String teacherName) throws IOException {
        List<String> lines = new ArrayList<>();
        boolean inTeacherSection = false;
        boolean teacherFound = false;
        String teacherStartTag = "<teacher: " + teacherName + ">";
        String teacherEndTag = "</teacher: " + teacherName + ">";

        // Чтение файла и сохранение содержимого в список строк
        try (BufferedReader br = new BufferedReader(new FileReader(FILE_PATH))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        }

        // Поиск и удаление блока данных учителя
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_PATH))) {
            for (String line : lines) {
                if (line.trim().equals(teacherStartTag)) {
                    inTeacherSection = true;
                    teacherFound = true;
                    continue;
                }

                if (line.trim().equals(teacherEndTag)) {
                    inTeacherSection = false;
                    continue;
                }

                if (!inTeacherSection) {
                    bw.write(line.trim());
                    bw.newLine();
                }
            }
        }

        return teacherFound;
    }
    
    public static void addLesson(String groupName, String teacherName, String subjectName, String year, String month) throws IOException {
        List<String> lines = readFile();
        List<String> updatedLines = new ArrayList<>();
        boolean groupFound = false;

        for (String line : lines) {
            updatedLines.add(line);
            if (line.contains("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>")) {
                groupFound = true;
                updatedLines.add("<Lesson: year:" + year + ", month:" + month + ">");
                updatedLines.add("</Lesson: year:" + year + ", month:" + month + ">");
            }
        }

        if (!groupFound) {
            updatedLines.add("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
            updatedLines.add("<Lesson: year:" + year + ", month:" + month + ">");
            updatedLines.add("</Lesson: year:" + year + ", month:" + month + ">");
            updatedLines.add("</Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
        }

        Files.write(Paths.get(FILE_PATH), updatedLines, StandardCharsets.UTF_8);
    }

    public static void addDay(String groupName, String teacherName, String subjectName, String year, String month, String day, List<GradeEntry> grades) throws IOException {
        List<String> lines = readFile();
        List<String> updatedLines = new ArrayList<>();
        boolean groupFound = false;

        for (String line : lines) {
            updatedLines.add(line);
            if (line.contains("<Lesson: year:" + year + ", month:" + month + ">")) {
                updatedLines.add("<Day: " + day + ">");
                for (GradeEntry grade : grades) {
                    updatedLines.add(grade.getStudentId() + "; " + grade.getStudentName() + "; " + (grade.isPresence() ? "Present" : "Absent") + "; " + grade.getGrade());
                }
                updatedLines.add("</Day: " + day + ">");
                groupFound = true;
            }
        }

        if (!groupFound) {
            updatedLines.add("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
            updatedLines.add("<Lesson: year:" + year + ", month:" + month + ">");
            updatedLines.add("<Day: " + day + ">");
            for (GradeEntry grade : grades) {
                updatedLines.add(grade.getStudentId() + "; " + grade.getStudentName() + "; " + (grade.isPresence() ? "Present" : "Absent") + "; " + grade.getGrade());
            }
            updatedLines.add("</Day: " + day + ">");
            updatedLines.add("</Lesson: year:" + year + ", month:" + month + ">");
            updatedLines.add("</Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>");
        }

        Files.write(Paths.get(FILE_PATH), updatedLines, StandardCharsets.UTF_8);
    }
    
    public static List<Student> getStudents(String groupName) {
        List<Student> students = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) {
            String line;
            boolean isGroupFound = false;
            while ((line = reader.readLine()) != null) {
                if (line.contains("<Group: " + groupName + ">")) {
                    isGroupFound = true;
                    continue;
                }
                if (line.startsWith("</Group:")) {
                    if (isGroupFound) {
                        break; // Конец данных для группы
                    } else {
                        continue; // Пропускаем данные других групп
                    }
                }
                if (isGroupFound) {
                    String[] parts = line.split("; ");
                    if (parts.length == 2) {
                        students.add(new Student(parts[0], parts[1], groupName));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return students;
    }
    
    public static List<String> countLessonDays(String groupName, String teacherName, String subjectName, String year, String month) {
        List<String> days = new ArrayList<>();

        try {
            BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
            String line;
            boolean inGroup = false;
            boolean inLesson = false;
            boolean inCorrectLesson = false;

            // Создаем паттерн для считывания дней в lesson указанного года и месяца
            Pattern dayPattern = Pattern.compile("<Day: (\\d+)>");
            while ((line = reader.readLine()) != null) {
                if (line.contains("<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>")) {
                    inGroup = true;
                    continue;
                }

                if (inGroup && line.equals("<Lesson: year:" + year + ", month:" + month + ">")) {
                    inLesson = true;
                    inCorrectLesson = true; // Начинаем считывать lesson этого года и месяца
                    continue;
                }

                if (inGroup && inCorrectLesson && line.startsWith("</Lesson:")) {
                    inLesson = false;
                    inCorrectLesson = false; // Заканчиваем считывать lesson этого года и месяца
                    break; // Выходим из цикла после окончания lesson
                }

                if (inGroup && inLesson) {
                    Matcher matcher = dayPattern.matcher(line);
                    if (matcher.find()) {
                        String day = matcher.group(1);
                        days.add(day);
                    }
                }
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return days;
    }
    
    public static List<Student> readStudentsFromFile(String filePath) throws IOException {
        List<Student> students = new ArrayList<>();
        System.out.println("Try");
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            String currentGroup = null;
            
            while ((line = br.readLine()) != null) {
                line = line.trim();
                
                // Check if the line defines a group
                if (line.startsWith("<Group:")) {
                    currentGroup = line.split(":")[1].replace(">", "").trim();
                } else if (!line.isEmpty() && !line.startsWith("</Group")) {
                    // This line contains student data
                    String[] studentData = line.split(";");
                    if (studentData.length == 2) {
                        String id = studentData[0].trim();
                        String name = studentData[1].trim();
                        students.add(new Student(id, name, currentGroup));
                    }
                }
            }
        }
        
        return students;
    }
    
    public static List<StudentDay> getStudentJournalForDay(String groupName, String teacherName, String subjectName, String year, String month, int day) throws IOException {
        List<StudentDay> studentJournal = new ArrayList<>();
        String filePath = "E:\\JavaProjects\\Journal\\src\\main\\webapp\\data\\data.txt"; // Укажите путь к вашему текстовому файлу

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            String currentGroup = null;
            String currentTeacher = null;
            String currentSubject = null;
            String currentYear = null;
            String currentMonth = null;
            boolean lessonFound = false;
            boolean dayFound = false;

            while ((line = br.readLine()) != null) {
                line = line.trim();

                // Ищем информацию о группе, учителе, предмете и дне
                if (line.startsWith("<Group:")) {
                    currentGroup = line.split(":")[1].replace(">", "").trim();
                    currentTeacher = null;
                    currentSubject = null;
                    currentYear = null;
                    currentMonth = null;
                } else if (line.startsWith("<teacher:") && line.contains(teacherName)) {
                    currentTeacher = teacherName;
                } else if (line.startsWith("<Subject:") && line.contains(subjectName)) {
                    currentSubject = subjectName;
                } else if (line.startsWith("<Lesson:") && line.contains("year:" + year) && line.contains("month:" + month)) {
                    currentYear = year;
                    currentMonth = month;
                    lessonFound = true;
                } else if (line.startsWith("</Lesson:") && lessonFound) {
                    lessonFound = false;
                } else if (line.startsWith("<Day:") && lessonFound) {
                    int currentDay = Integer.parseInt(line.split(":")[1].replace(">", "").trim());
                    if (currentDay == day) {
                        dayFound = true;
                    } else {
                        dayFound = false;
                    }
                } else if (!line.startsWith("</Day:") && dayFound) {
                    // Эта строка содержит информацию о присутствии и оценках студентов
                    String[] studentData = line.split(";");
                    if (studentData.length == 4) {
                        String id = studentData[0].trim();
                        String name = studentData[1].trim();
                        String presence = studentData[2].trim();
                        String grade = studentData[3].trim();
                        studentJournal.add(new StudentDay(id, name, groupName, presence, grade));
                    }
                } else if (line.startsWith("</Day:") && dayFound) {
                    // Дошли до конца дня, выходим из цикла
                    break;
                }
            }
        }

        return studentJournal;
    }
    
    public static void updateLessonData(String teacherName, String subjectName, String groupName, String year, String month, List<GradeEntry> gradeEntries) throws IOException {
        File file = new File("E:\\JavaProjects\\Journal\\src\\main\\webapp\\data\\data.txt");
        List<String> lines = readLines(file);
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));

        boolean inLessonBlock = false;
        String startLessonTag = "<Lesson: year:" + year + ", month:" + month + ">";
        String endLessonTag = "</Lesson: year:" + year + ", month:" + month + ">";
        String lessonHeader = "<Group: " + groupName + ";Teacher: " + teacherName + ";Subject: " + subjectName + ";>";

        for (String line : lines) {
            if (line.trim().equals(startLessonTag)) {
                inLessonBlock = true;
                continue;
            }
            if (line.trim().equals(endLessonTag)) {
                inLessonBlock = false;
                continue;
            }
            if (!inLessonBlock) {
                writer.write(line);
                writer.newLine();
                if (line.trim().equals(lessonHeader)) {
                    writer.write(startLessonTag);
                    writer.newLine();
                    Set<Integer> daysSet = gradeEntries.stream()
                            .map(entry -> Integer.parseInt(entry.getDay()))
                            .collect(Collectors.toSet());
                    List<Integer> days = new ArrayList<>(daysSet);
                    Collections.sort(days);
                    for (int day : days) {
                        final int currentDay = day;
                        List<GradeEntry> dayEntries = gradeEntries.stream()
                                .filter(entry -> Integer.parseInt(entry.getDay()) == currentDay)
                                .collect(Collectors.toList());
                        if (!dayEntries.isEmpty()) {
                            writer.write("<Day: " + day + ">");
                            writer.newLine();
                            for (GradeEntry entry : dayEntries) {
                                writer.write(entry.getStudentId() + "; " + entry.getStudentName() + "; " + (entry.isPresence() ? "Present" : "Absent") + "; " + entry.getGrade());
                                writer.newLine();
                            }
                            writer.write("</Day: " + day + ">");
                            writer.newLine();
                        }
                    }
                    writer.write(endLessonTag);
                    writer.newLine();
                }
            }
        }

        writer.close();
    }

    private static List<String> readLines(File file) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        List<String> lines = new ArrayList<>();
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        reader.close();
        return lines;
    }

    
}