summaryrefslogtreecommitdiff
path: root/src/main/java/design/controller/userinput/menus/ImportExportMenu.java
blob: 21ffa6c64e28efee4bdd0fd35424071ba34fa011 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package design.controller.userinput.menus;

import design.controller.userinput.Menu;
import design.controller.userinput.MenuOption;
import design.persistence.*;
import design.persistence.importexport.DataHandler;
import design.persistence.importexport.DataSource;
import design.persistence.importexport.JSONHandler;
import design.persistence.importexport.XMLHandler;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

public class ImportExportMenu extends Menu {

    @Override
    public String getTitle() {
        return "import export menu";
    }

   @Override
    public List<MenuOption> getMenuOptions() {
        List<MenuOption> opts = new java.util.ArrayList<>();


        opts.add(new MenuOption("return to main menu", () -> new MainMenu().present()));

        opts.add(new MenuOption("import leagues...", () -> promptForPath(true, false)));
        opts.add(new MenuOption("export leagues...", () -> promptForPath(false, false)));
        opts.add(new MenuOption("import profiles...", () -> promptForPath(true, true)));
        opts.add(new MenuOption("export profiles...", () -> promptForPath(false, true)));

        return opts;
    }

    private void promptForPath(boolean isImporting, boolean isPersonalProfile)
    {
        System.out.print("Enter file path: ");
        Scanner sc = new Scanner(System.in);
        String filePath = sc.nextLine();
        File file = new File(filePath);

        DataSource source;
        if (isPersonalProfile) {
            source = PersonalDatabase.instance();
        } else {
            source = LeagueDatabase.instance();
        }

        DataHandler handler;
        String ext = getExtension(filePath);
        switch (ext) {
            case "json" -> handler = new JSONHandler(source);
            case "xml" -> handler = new XMLHandler(source);
            default -> {
                System.out.println("Unsupported file type: " + ext);
                this.present();
                return;
            }
        }

        try {
            if (isImporting) {
                handler.importData(file);
            } else {
                handler.exportData(file);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        this.present();
    }

    private static String getExtension(String fileName) {
        int i = fileName.lastIndexOf('.');
        return (i >= 0) ? fileName.substring(i + 1).toLowerCase() : "unknown";
    }
}