Skip to content

Commit

Permalink
Api support
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryanidk committed Mar 14, 2024
1 parent 7c0a4c8 commit bea755b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 79 deletions.
101 changes: 30 additions & 71 deletions lib/screens/send_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import 'package:flutter/services.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:gsheets/gsheets.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class SendData extends StatefulWidget {
Expand Down Expand Up @@ -39,7 +40,8 @@ class _SendDataState extends State<SendData> {
void initState() {
super.initState();
getLocalGames().then((_) {
setState(() {}); //refresh, very unpracitical but this is a hotfix after all :P ...
setState(
() {}); //refresh, very unpracitical but this is a hotfix after all :P ...
});
}

Expand All @@ -51,85 +53,40 @@ class _SendDataState extends State<SendData> {
}
}

Future<void> loadEnv() async {
String envString;
try {
envString = await rootBundle.loadString('.env');
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('The .env file could not be found')),
);
return;
Future<Map> fetchApi(String key) async {
var a = await http.get(Uri.parse(
'https://ryanidkproductions.com/api/mergedata?key=$key')); // temp api host
if (a.statusCode == 200) {
return jsonDecode(a.body);
} else {
return {"Error": "Invalid API key"};
}
}

try {
await dotenv.load(fileName: ".env").timeout(Duration(seconds: 5));
_gsheets = GSheets(dotenv.env['GOOGLE_SHEETS_DATA']!);
_spreadsheetId = dotenv.env['SPREADSHEET_ID']!;
_gameWorksheetName = dotenv.env['GAME_WORKSHEET_NAME']!;
_pitWorksheetName = dotenv.env['PIT_WORKSHEET_NAME']!;
_passcode = dotenv.env['PASSCODE']!;
} on TimeoutException catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Loading environment variables timed out')),
);
} catch (e) {
Future<void> loadApi() async {
final prefs = await SharedPreferences.getInstance();
String apiKey = prefs.getString('apiKey') ?? '';
Map apiResponse = await fetchApi(apiKey);

if (apiResponse.containsKey("Error")) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('An error occurred while loading environment variables')),
SnackBar(content: Text('Invalid or no API key entered')),
);
} else {
_gsheets = GSheets(apiResponse["GOOGLE_SHEETS_DATA"]);
_spreadsheetId = apiResponse["SPREADSHEET_ID"];
_gameWorksheetName = apiResponse["GAME_WORKSHEET_NAME"];
_pitWorksheetName = apiResponse["PIT_WORKSHEET_NAME"];
}
}

Future<void> saveDataLocally() async {
final prefs = await SharedPreferences.getInstance();
final savedGames = prefs.getStringList('savedGames') ?? [];
savedGames.add(jsonEncode(widget.data));
await prefs.setStringList('savedGames', savedGames);
}

Future<void> validate() async {
await loadEnv();
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isAuthenticated = prefs.getBool('isAuthenticated') ?? false;

/*if (!isAuthenticated) {
String? passcode;
await showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Enter passcode'),
content: TextField(
obscureText: true,
onChanged: (value) {
passcode = value; // Update passcode
},
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
);
},
);
if (passcode == dotenv.env['PASSCODE']) {
await prefs.setBool('isAuthenticated', true);
sendDataToGoogleSheets();
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Wrong passcode!")),
);
}
} else { // already authenticated
sendDataToGoogleSheets();
}*/
}

Future<void> sendDataToGoogleSheets() async {
String message = '';

Expand Down Expand Up @@ -171,7 +128,7 @@ class _SendDataState extends State<SendData> {
}
}
} catch (e) {
message = 'Shep Error!: $e';
message = 'Could not send data to sheets!';
print(e);
}

Expand All @@ -183,7 +140,7 @@ class _SendDataState extends State<SendData> {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: loadEnv(),
future: loadApi(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Scaffold(
Expand Down Expand Up @@ -241,7 +198,8 @@ class _SendDataState extends State<SendData> {
padding: EdgeInsets.all(15),
child: Text(
savedGamesArray.join('\n\n\n'),
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
),
if (showQR)
Expand Down Expand Up @@ -358,7 +316,8 @@ class _SendDataState extends State<SendData> {
);
},
);
validate().then((_) { //send to google sheets, but authenticate first
sendDataToGoogleSheets().then((_) {
//send to google sheets, but authenticate first
if (!isCancelled) {
Navigator.of(context).pop();
}
Expand Down
22 changes: 14 additions & 8 deletions lib/screens/start.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ class _StartState extends State<StartPage> {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
SendData(data: {}, isGame: true, justSend: true),
builder: (context) => SendData(data: {}, isGame: true, justSend: true),
),
);
}
Expand Down Expand Up @@ -98,7 +97,8 @@ class _StartState extends State<StartPage> {
decoration: InputDecoration(
hintText: "API Key",
suffixIcon: IconButton(
icon: Icon(obscureText ? Icons.visibility_off : Icons.visibility),
icon: Icon(
obscureText ? Icons.visibility_off : Icons.visibility),
onPressed: () {
setState(() {
obscureText = !obscureText;
Expand Down Expand Up @@ -152,15 +152,17 @@ class _StartState extends State<StartPage> {
builder: (BuildContext context) {
return AlertDialog(
title: Text('Delete all local games?'),
content: Text('This action cannot be undone!!', style: TextStyle(color: Colors.red)),
content: Text('This action cannot be undone!!',
style: TextStyle(color: Colors.red)),
actions: [
TextButton(
child: Text('Yes'),
onPressed: () {
deleteAllGames();
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('All local games deleted.')),
SnackBar(
content: Text('All local games deleted.')),
);
},
),
Expand Down Expand Up @@ -212,7 +214,8 @@ class _StartState extends State<StartPage> {
children: <Widget>[
ElevatedButton(
onPressed: matchScouting,
child: const Text("Match Scouting", style: TextStyle(fontSize: 28)),
child:
const Text("Match Scouting", style: TextStyle(fontSize: 28)),
),
const Padding(padding: EdgeInsets.all(10)),
ElevatedButton(
Expand All @@ -226,7 +229,9 @@ class _StartState extends State<StartPage> {
),
const Padding(padding: EdgeInsets.all(10)),
StreamBuilder<List<String>>(
stream: Stream.periodic(Duration(seconds: 1)).asyncMap((_) => SharedPreferences.getInstance().then((prefs) => prefs.getStringList('savedGames') ?? [])),
stream: Stream.periodic(Duration(seconds: 1)).asyncMap((_) =>
SharedPreferences.getInstance().then(
(prefs) => prefs.getStringList('savedGames') ?? [])),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return ElevatedButton(
Expand All @@ -236,7 +241,8 @@ class _StartState extends State<StartPage> {
} else {
return ElevatedButton(
onPressed: sendData,
child: Text('Upload Local Saves (${snapshot.data!.length})', style: TextStyle(fontSize: 28)),
child: Text('Upload Local Saves (${snapshot.data!.length})',
style: TextStyle(fontSize: 28)),
);
}
},
Expand Down

0 comments on commit bea755b

Please sign in to comment.