summaryrefslogtreecommitdiff
path: root/src/main/java/design/controller/userinput/menus/ImportExportMenu.java
blob: db861c506ca49f5a5ba0e8ae7bf1e3386c981f0f (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
package design.controller.userinput.menus;

import design.controller.userinput.Menu;
import design.controller.userinput.MenuOption;
import design.persistence.JSONHandler;
import design.persistence.XMLHandler;

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

import design.model.DataHandler;

public class ImportExportMenu extends Menu {
    private static final Map<String, DataHandler> handlers = Map.of(
    "xml", new XMLHandler(),
    "json", new JSONHandler()
    );

    @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 league...", () -> promptForPath(true, false)));
        opts.add(new MenuOption("export league...", () -> promptForPath(false, false)));
        opts.add(new MenuOption("import personal profile...", () -> promptForPath(true, true)));
        opts.add(new MenuOption("export personal profile...", () -> promptForPath(false, true)));

        return opts;
    }

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

        String ext = getExtension(filePath);
        DataHandler handler = handlers.get(ext);

        if (handler == null) {
            System.out.println("Unsupported file type: " + ext);
            return;
        }

        try {
            if (isImporting) {
                if (isPersonalProfile)
                    handler.importPersonalData(file);
                else
                    handler.importLeagueData(file);
            } else {
                if (isPersonalProfile)
                    handler.exportPersonalData(file);
                else
                    handler.exportLeagueData(file);
            }
        } catch (IOException e) {
            System.err.println("I/O error: " + e.getMessage());
        }
    }

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