import java.io.*;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class Lib {
    public static List<String> memory = new ArrayList<>(); //存取输出过的选手信息或赛程信息

    public Lib() {
        for (int i = 0; i < 25; i++) {
            memory.add(i , "");
        }
    }

    //对input.txt里的内容进行读取并转换成字符串列表
    public static List<String> getInput(String path) throws IOException {
        List<String>  enter = new ArrayList();
        File file = new File(path);
        if (!file.exists()) {
            System.out.println("文件不存在!");
            System.exit(0);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path) , "UTF-8"));
        String line = "";
        while ((line = reader.readLine()) != null) {
            if (!line.equals("")) //如果是空行则跳过
                enter.add(getInstruction(line));
        }
        reader.close();
        return enter;
    }

    //对input.txt里的指令进行处理，返回处理后的字符串
    public static String getInstruction(String instruction) {
        String regex="\\s+"; //删去头尾空格
        String i[] = instruction.trim().split(regex);
        if (i[0].equals("players")) {
            if (i.length == 1)
                return "players";
            else
                return "Error";
        }
        else if (i[0].equals("result")) {
            if (i.length == 2) {
                String d = i[1];
                if (d.equals("Q1"))
                    return "0109";
                if (d.equals("Q2"))
                    return "0110";
                if (d.equals("Q3"))
                    return "0111";
                if (d.equals("Q4"))
                    return "0112";
                if(isDate(i[1]))
                    return d;
                return "N/A";
            }
            else
                return "N/A";
        }
        else
            return "Error";
    }

    //判断日期是否合法
    public static boolean isDate(String d) {
        String regex = "\\d{4}"; //日期应为数字并且长度为4
        if (!d.matches(regex))
            return false;
        int date = Integer.valueOf(d);
        if (date < 116 || date > 129) //日期不在澳大利亚网球公开赛期间
            return false;
        return true;
    }

    //解析选手信息
    public static String parsePlayers() throws IOException {
        String path = "src/data/players.json"; //路径
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path) , "UTF-8"));
        Gson gson = new Gson(); //利用Gson解析数据
        Players i = gson.fromJson(reader , Players.class);
        List<Players.Player> playerList = i.players;
        String pl = "";
        for (Players.Player p:playerList) { //获取选手信息
            String s="";
            if (p.gender.equals("M"))
                s="male";
            else
                s="female";
            pl += "full_name:" + p.full_name + "\n"
                    + "gender:" + s +"\n"
                    + "nationality:" + p.nationality.name + "\n"
                    + "-----" + "\n";
        }
        reader.close();
        return pl;
    }

    //解析赛程信息
    public static String parseSchedule(String date) throws IOException {
        String path = "src/data/schedule/"+ date + ".json"; //路径
        Gson gson = new Gson(); //利用Gson解析数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path) , "UTF-8"));
        Schedule schedule = gson.fromJson(reader , Schedule.class);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < schedule.matches.size(); i++) {
            if (schedule.matches.get(i).match_status.code.equals("W")) { //判断是否弃赛
                result.append("W/O");
                result.append("\n" + "-----" + "\n");
            }
            else {
                result.append("time:");
                result.append(schedule.matches.get(i).actual_start_time); //获取比赛实际开始时间
                result.append("\n");
                result.append("winner:");
                List<String> p1 = new ArrayList<>(); //存放选手1的比分
                List<String> p2 = new ArrayList<>(); //存放选手2的比分
                for (int j = 0; j < schedule.matches.get(i).teams.size(); j++) {
                    if (schedule.matches.get(i).teams.get(j).status != null) {
                        String shortname = getShortname(schedule.matches.get(i).teams.get(j).team_id , schedule); //获取比赛胜利者的名字缩写
                        result.append(shortname);
                        result.append("\n");
                        result.append("score:");
                    }
                    for (int k = 0; k < schedule.matches.get(i).teams.get(j).score.size(); k++) { //将每位选手比分存入对应列表
                        if (j == 0) {
                            p1.add(schedule.matches.get(i).teams.get(j).score.get(k).game);
                        }
                        if (j == 1)
                            p2.add(schedule.matches.get(i).teams.get(j).score.get(k).game);
                    }
                }
                int m ;
                for (m = 0; m < p1.size() - 1; m++) { //获取每场比赛的比分
                    result.append(p1.get(m));
                    result.append(":");
                    result.append(p2.get(m));
                    result.append(" | ");
                }
                result.append(p1.get(m));
                result.append(":");
                result.append(p2.get(m));
                result.append("\n" + "-----" + "\n");

            }
        }
        String s = result.toString();
        return s;
    }

    //获得比赛胜利者的名字缩写
    public static String getShortname(String team_id, Schedule schedule) {
        List<String> shortname = new ArrayList<>();
        for (int i = 0; i < schedule.teams.size(); i++) {
            if (schedule.teams.get(i).uuid.equals(team_id)){ //利用team_id找到选手相对应的队
                for (int j = 0; j < schedule.teams.get(i).players.size(); j++) {
                    for (int k = 0; k < schedule.players.size(); k++) {
                        if (schedule.players.get(k).uuid.equals(schedule.teams.get(i).players.get(j))) //利用选手的uuid找到相应的选手
                            shortname.add(schedule.players.get(k).short_name);
                    }
                }
            }
        }
        String name = shortname.get(0);
        if (shortname.size() > 1) { //该场为团体比赛
            for (int m = 1; m < shortname.size(); m++) {
                name += " & " + shortname.get(m);
            }
        }
        return name;
    }

    //将解析后的数据写入文件
    public static void getOutput(List<String> input,String path) throws IOException {
        File file = new File(path);
        if (!file.exists())
            file.createNewFile(); //如果文件不存在，则新建文件
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path) , "UTF-8"));
        boolean pflag = false; //标记之前是否输出过players
        boolean[] sflag = new boolean[25]; //标记之前是否输出过每个日期的赛程
        for (int i = 0; i < 25; i++) {
            sflag[i] = false;
        }
        for (String i:input) {
            if(i.equals("Error")) {
                writer.write("Error" + "\n" + "-----" + "\n");
            }
            else if (i.equals("N/A")) {
                writer.write("N/A" + "\n" + "-----" + "\n");
            }
            else if (i.equals("players")) {
                if (!pflag) { //如果从未输出过players
                    String s = parsePlayers();
                    memory.add(0 , s);
                    pflag = true;
                }
                writer.write(memory.get(0)); //之前输出过players，则直接从列表中取数据
            }
            else {
                int date = Integer.valueOf(i);
                date = date % 109 + 1;
                if (!sflag[date]) { //如果从未输出过players
                    String s = parseSchedule(i);
                    memory.add(date , s);
                    sflag[date] = true;
                }
                writer.write(memory.get(date));
            }
        }
        writer.close();
    }
}
