package chapter_12_solution;

import java.io.*;
import java.util.*;

public class TextFileDatabase {

    private static final String FILE_PATH = "database.txt";

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.print("请输入患者姓名" + "\n" +"（输入 'exit' 退出录入，输入 'print' 打印输出目前库中所有患者）: ");
            String inputName = scanner.nextLine();
            // 输入exit时退出循环
            if (inputName.equalsIgnoreCase("exit")) {
                break;
            }

            // 输入exit时退出循环
            if (inputName.equalsIgnoreCase("print")) {
                printAllPatients();
                break;
            }

            System.out.print("请输入患者身份证号码: ");
            String inputIdCardNo = scanner.nextLine();

            System.out.print("请输入患者电话号码: ");
            String inputPhoneNumber = scanner.nextLine();

            System.out.print("请输入患者地址: ");
            String inputAddress = scanner.nextLine();

            Patient patient = new Patient(inputName, inputIdCardNo, inputPhoneNumber, inputAddress);
            addPatient(patient);
            System.out.println("患者信息已录入！");
        }
        scanner.close();
    }

    public static void addPatient(Patient patient) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true))) {
            writer.write(
                    patient.getName() + ',' +
                            patient.getIdCardNo() + ',' +
                            patient.getPhoneNumber() + ',' +
                            patient.getAddress());
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void printAllPatients() {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH));
            String line;
            while ((line = reader.readLine()) != null) {
                // 输出文件内容
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
