Skip to content
Snippets Groups Projects
viewevents.dart 10.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'datamodel.dart';
    
    import 'package:http/http.dart' as http;
    
    
    Maximilian Betz's avatar
    Maximilian Betz committed
    class ViewEvents extends StatefulWidget {
      const ViewEvents({Key? key}) : super(key: key);
    
    Maximilian Betz's avatar
    Maximilian Betz committed
      @override
      _ViewEvents createState() => _ViewEvents();
    }
    
    Maximilian Betz's avatar
    Maximilian Betz committed
    class _ViewEvents extends State<ViewEvents> {
      int _synccounter = 0;  //For displaying progress during event upload
    
    Maximilian Betz's avatar
    Maximilian Betz committed
    
    
      Future<String?> login() async {
        String? token;
        ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
    
        String url = 'https://sandbox.sensor.awi.de/rest/sensors/contacts/login';
        debugPrint("Start login to : " + url);
    
        Map<String, dynamic> body = {'username': configuration.loginInformation.mail, 'authPassword': configuration.loginInformation.password};
        String encodedBody = body.keys.map((key) => "$key=${body[key]}").join("&");
        debugPrint(encodedBody);
    
        final response = await http.post(Uri.parse(url),
            body: encodedBody,
            headers: {
              'Accept' : 'application/json',
              'Content-Type' : 'application/x-www-form-urlencoded'
            },
            encoding: Encoding.getByName("utf-8")
        );
    
        if (response.statusCode == 200) {
          debugPrint('Login success');
          //TODO: display feedback to user that credentials are correct
    
          token = response.headers['set-cookie']?.split(';')[0];
    
          debugPrint("Token:" + token!);
          debugPrint(response.body.toString());
          debugPrint(response.headers.toString());
          debugPrint(response.headers['set-cookie']);
    
    
        } else {
          debugPrint('Header: ' + response.headers.toString());
          debugPrint('Body: ' + response.body.toString());
          debugPrint('StatusCode: ' + response.statusCode.toString());
          throw Exception('Failed to login');
    
    
        }
        return token;
      }
    
    
    Maximilian Betz's avatar
    Maximilian Betz committed
      Future<bool> syncEvents() async {
        final EventStoreInstance events = EventStoreInstance();
        final ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
    
        String? token = await login();
    
        if (token != null) {
          String baseUrl = 'https://sandbox.sensor.awi.de/rest/sensors/events/putEvent/';
          String url = '';
    
          _synccounter = events.getPendingEventCount();
          debugPrint('Number of Events: ' + events.events.length.toString());
          debugPrint('Number of Pending Events: ' + _synccounter.toString());
          var index = 0;
          for (var event in events.events) {
            if (event.status == 'PENDING') {
              debugPrint('Idx: ' + index.toString() + ' ' +
                  event.toSensorJson().toString());
              index++;
    
              url = baseUrl + event.id.toString() + '?createVersion=false';
              debugPrint('XXX ' + Uri.parse(url).toString());
              final response = await http.put(Uri.parse(url),
                headers: {
                  "Content-Type": "application/json",
                  "Cookie": token
                },
                body: event.toSensorJson().toString(),
                encoding: Encoding.getByName("utf-8"),
              );
    
              if (response.statusCode == 201) {
                _synccounter--;
                debugPrint(
                    'put success, remaining events: ' + _synccounter.toString());
                event.status =
                'EXPORTED'; //Update event status so that it is only exported once.
    
    
                setState(() {});
    
                debugPrint(response.body.toString());
                debugPrint(response.headers.toString());
                debugPrint(response.headers['set-cookie']);
              } else {
                debugPrint('Header: ' + response.headers.toString());
                debugPrint('Body: ' + response.body.toString());
                debugPrint('StatusCode: ' + response.statusCode.toString());
                throw Exception('Failed to put.');
              }
    
    Maximilian Betz's avatar
    Maximilian Betz committed
            }
          }
    
    Maximilian Betz's avatar
    Maximilian Betz committed
        }
    
        return false;
    
    Maximilian Betz's avatar
    Maximilian Betz committed
      }
    
    Maximilian Betz's avatar
    Maximilian Betz committed
    
    
      @override
      Widget build(BuildContext context) {
        // Get singleton to access locally stored events:
        final EventStoreInstance events = EventStoreInstance();
        return Scaffold(
          appBar: AppBar(
            title: const Text("View Added Events"),
          ),
          body: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: DataTable(
                columns: const <DataColumn>[
                  DataColumn(
                    label: Text(
                      'Id',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'URN',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Label',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Type',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Description',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
    
                  DataColumn(
                    label: Text(
                      'StartDate',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'EndDate',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
    
                  DataColumn(
                    label: Text(
                      'Latitude',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Longitude',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'Elevation',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
    
                  DataColumn(
                    label: Text(
                      'Status',
                      style: TextStyle(fontStyle: FontStyle.italic),
                    ),
                  ),
                ],
                rows: <DataRow>[
    
                  for (var event in events.events)
    
                    DataRow(
                      cells: <DataCell>[
                        DataCell(Text(event.id.toString())),
                        DataCell(Text(event.urn)),
                        DataCell(
                          TextFormField(
    
                            readOnly: true,
    
                            initialValue: event.label,
                            onFieldSubmitted: (val) {
                              event.label = val; //Update Database
                            },
                          ),
                        ),
                        DataCell(Text(event.type)),
                        DataCell(
                          TextFormField(
    
                            readOnly: true,
    
                            initialValue: event.description,
                            onFieldSubmitted: (val) {
                              event.description = val; //Update Database
                            },
                          ),
                        ),
    
                        DataCell(Text(event.startDate)),
                        DataCell(Text(event.endDate)),
    
                          TextFormField(
                            readOnly: true,
                            initialValue: event.latitude,
                            onFieldSubmitted: (val) {
                              event.latitude = val; //Update Database
                            },
                          ),
                        ),
                        DataCell(
                          TextFormField(
                            readOnly: true,
                            initialValue: event.longitude,
                            onFieldSubmitted: (val) {
                              event.longitude = val; //Update Database
                            },
                          ),
                        ),
                        DataCell(
                          TextFormField(
                            readOnly: true,
                            initialValue: event.elevation,
                            onFieldSubmitted: (val) {
                              event.elevation = val; //Update Database
                            },
                          ),
                        ),
                        DataCell(
                          TextFormField(
                            readOnly: true,
                            initialValue: event.status,
                            onFieldSubmitted: (val) {
                              event.status = val; //Update Database
                            },
    
          bottomNavigationBar: Row(
    
            mainAxisAlignment: MainAxisAlignment.end,
    
            children: [
    
              FloatingActionButton.extended(
                heroTag: null,
                tooltip: 'Upload Events',
                icon: null,
    
                label: const Text('Sync'),
    
                onPressed: () {
    
    Maximilian Betz's avatar
    Maximilian Betz committed
    
                  syncEvents();
    
    Maximilian Betz's avatar
    Maximilian Betz committed
                  //  barrierDismissible: false,
    
                  //  context: context,
                  //  builder: (BuildContext context) => _buildPopupDialog(context),
                  //);
    
    Maximilian Betz's avatar
    Maximilian Betz committed
      Widget _buildPopupDialog(BuildContext context) {
    
        return AlertDialog(
          title: const Text('Uploading Events'),
    
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              //Text("Progress"),
              const CircularProgressIndicator(),
              const SizedBox(height: 10),
              Text('Remaining events to sync: ' + _synccounter.toString()),
            ],
    
    Maximilian Betz's avatar
    Maximilian Betz committed
          actions: <Widget>[
            TextButton(
              onPressed: () {
                //syncEvents();
    
                setState(() {
    
                });
                //Navigator.of(context).pop();
              },
              //textColor: Theme.of(context).primaryColor,
              child: const Text('Close'),
            ),
          ],
        );
      }
    
    
    
    
    //TODO: allow editing fields here. Check validation of input value!