summaryrefslogtreecommitdiff
path: root/lib/level_selection.dart
blob: 0c1a0fef524c0f5317d67347d2234283a3eefd46 (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import 'dart:io';

import 'package:esense_flutter/esense.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sense_the_rhythm/esense_connect_dialog.dart';
import 'package:sense_the_rhythm/simfile.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'level.dart';

class LevelSelection extends StatefulWidget {
  const LevelSelection({super.key});

  @override
  State<LevelSelection> createState() => _LevelSelectionState();
}

class _LevelSelectionState extends State<LevelSelection> {
  String? stepmaniaCoursesPath;
  List<Simfile> stepmaniaCoursesFolders = [];

  String eSenseDeviceName = '';
  ESenseManager? eSenseManager;
  ValueNotifier<String> _deviceStatus = ValueNotifier('');
  // String _deviceStatus = '';
  bool connected = false;
  bool sampling = false;

  @override
  void initState() {
    super.initState();
    _listenToESense();
    loadFolderPath();
  }

  Future<void> _askForPermissions() async {
    if (!(await Permission.bluetoothScan.request().isGranted &&
        await Permission.bluetoothConnect.request().isGranted)) {
      print(
          'WARNING - no permission to use Bluetooth granted. Cannot access eSense device.');
    }
    // for some strange reason, Android requires permission to location for Bluetooth to work.....?
    if (Platform.isAndroid) {
      if (!(await Permission.locationWhenInUse.request().isGranted)) {
        print(
            'WARNING - no permission to access location granted. Cannot access eSense device.');
      }
    }
  }

  Future<void> _listenToESense() async {
    await _askForPermissions();

    // if you want to get the connection events when connecting,
    // set up the listener BEFORE connecting...
    eSenseManager!.connectionEvents.listen((event) {
      print('CONNECTION event: $event');

      // when we're connected to the eSense device, we can start listening to events from it
      // if (event.type == ConnectionType.connected) _listenToESenseEvents();

      setState(() {
        connected = false;
        switch (event.type) {
          case ConnectionType.connected:
            _deviceStatus.value = 'connected';
            connected = true;
            break;
          case ConnectionType.unknown:
            _deviceStatus.value = 'unknown';
            break;
          case ConnectionType.disconnected:
            _deviceStatus.value = 'disconnected';
            sampling = false;
            break;
          case ConnectionType.device_found:
            _deviceStatus.value = 'device_found';
            break;
          case ConnectionType.device_not_found:
            _deviceStatus.value = 'device_not_found';
            break;
        }
      });
    });
  }

  Future<void> _connectToESense(String deviceName) async {
    if (!connected) {
      await _askForPermissions();
      print('Trying to connect to eSense device...');
      setState(() {
        eSenseDeviceName = deviceName;
      });
      print(eSenseDeviceName);
      eSenseManager = ESenseManager(eSenseDeviceName);
      connected = await eSenseManager!.connect();
      print('success!');

      setState(() {
        _deviceStatus.value = connected ? 'connecting...' : 'connection failed';
      });
    }
  }

  Future<void> loadFolderPath() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final String? stepmaniaCoursesPathSetting =
        prefs.getString('stepmania_courses');

    if (stepmaniaCoursesPathSetting == null) return;
    List<Simfile> stepmaniaCoursesFoldersFuture =
        await listFilesAndFolders(stepmaniaCoursesPathSetting);

    setState(() {
      stepmaniaCoursesPath = stepmaniaCoursesPathSetting;
      stepmaniaCoursesFolders = stepmaniaCoursesFoldersFuture;
    });
  }

  Future<void> selectFolder() async {
    String? selectedFolder = await FilePicker.platform.getDirectoryPath();

    if (selectedFolder != null) {
      // Save the selected folder path
      SharedPreferences prefs = await SharedPreferences.getInstance();
      await prefs.setString('stepmania_courses', selectedFolder);

      loadFolderPath();
    }
  }

  Future<List<Simfile>> listFilesAndFolders(String directoryPath) async {
    final directory = Directory(directoryPath);
    try {
      // List all files and folders in the directory
      return directory
          .listSync()
          .where((entity) => FileSystemEntity.isDirectorySync(entity.path))
          .map((entity) {
        Simfile simfile = Simfile(entity.path);
        simfile.load();
        return simfile;
      }).toList();
    } catch (e) {
      print("Error reading directory: $e");
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sense the Rhythm'),
        actions: [
          IconButton(
              onPressed: () => showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return ESenseConnectDialog(
                          deviceStatus: _deviceStatus,
                          connect: (String name) {
                            _connectToESense(name);
                          });
                    },
                  ),
              icon: const Icon(Icons.bluetooth))
        ],
      ),
      body: Builder(builder: (context) {
        if (stepmaniaCoursesPath == null) {
          return Text('Add a Directory with Stepmania Songs on \'+\'');
        } else if (stepmaniaCoursesFolders.isEmpty) {
          return Text(
              'Folder empty. Add Stepmania Songs to Folder or select a different folder on \'+\'');
        } else {
          return ListView.separated(
            itemCount: stepmaniaCoursesFolders.length,
            separatorBuilder: (BuildContext context, int index) =>
                const Divider(),
            itemBuilder: (context, index) {
              return ListTile(
                leading: Image.file(
                    File(stepmaniaCoursesFolders[index].bannerPath!)),
                trailing: Icon(Icons.play_arrow),
                title: Text(stepmaniaCoursesFolders[index].tags["TITLE"]!),
                subtitle: Text('3:45'),
                onTap: () => Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (BuildContext context) =>
                            Level(stepmaniaCoursesFolders[index]))),
              );
            },
          );
        }
      }),
      floatingActionButton: FloatingActionButton(
          onPressed: () => {selectFolder()}, child: Icon(Icons.add)),
    );
  }
}