Browse Source

isolating email contents generation

juan 1 month ago
parent
commit
bfc1232c06
1 changed files with 78 additions and 219 deletions
  1. 78 219
      lib/email.dart

+ 78 - 219
lib/email.dart

@@ -1,228 +1,87 @@
-// import 'package:flutter/material.dart';
-// import 'package:http/http.dart' as http;
-// import 'dart:convert';
-// import 'dart:ui_web' as ui;
-// import 'dart:html' as html;
+import 'package:flutter/material.dart';
+import 'api_service.dart';
+import 'structs.dart';
+import 'folder_drawer.dart';
 
-// // import 'package:flutter_html/flutter_html.dart';
 
-// class SerializableMessage {
-//   final String name;
-//   final String from;
-//   final String path;
-//   final String subject;
-//   final String date;
+class EmailListScreen extends StatelessWidget {
+  final List<GetThreadResponse> emails;
+  final Future<String> Function(List<String>) getEmailContent;
 
-//   SerializableMessage(
-//       {required this.name,
-//       required this.from,
-//       required this.path,
-//       required this.subject,
-//       required this.date});
+  EmailListScreen({required this.emails, required this.getEmailContent});
 
-//   factory SerializableMessage.fromJson(Map<String, dynamic> json) {
-//     return SerializableMessage(
-//         name: json['name'],
-//         from: json['from'],
-//         path: json['path'],
-//         subject: json['subject'],
-//         date: json['date']);
-//   }
-// }
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      appBar: AppBar(
+        title: Text('Emails'),
+      ),
+      body: ListView.separated(
+        itemCount: emails.length,
+        itemBuilder: (context, index) {
+          final email = emails[index];
+          return ListTile(
+            title: Text(email.from_name, style: TextStyle(fontWeight: FontWeight.bold)),
+            subtitle: Column(
+              crossAxisAlignment: CrossAxisAlignment.start,
+              children: [Text(email.subject)],
+            ),
+            trailing: Text(email.date.toString()),
+            onTap: () async {
+              String emailContent = await getEmailContent(email.messages);
+              Navigator.push(
+                context,
+                MaterialPageRoute(
+                  builder: (context) => EmailView(
+                    emailContent: emailContent,
+                    from: email.from_address,
+                    name: email.from_name,
+                    to: email.to.toString(),
+                    subject: email.subject,
+                    date: email.date.toString(),
+                    id: email.id.toString(),
+                  ),
+                ),
+              );
+            },
+          );
+        },
+        separatorBuilder: (context, index) => Divider(),
+      ),
+    );
+  }
+}
 
-// class EmailPage extends StatefulWidget {
-//   const EmailPage({super.key});
-//   final String title = 'cars';
 
-//   @override
-//   State<EmailPage> createState() => _EmailPageState();
-// }
+class EmailPage extends StatefulWidget {
+  @override
+  _EmailPageState createState() => _EmailPageState();
+}
 
-// class _EmailPageState extends State<EmailPage> {
-//   List emails = [];
-//   //  @override
-//   // void initState() {
-//   //   super.initState();
-//   // }
-//   //register the html element
-//   ui.platformViewRegistry.registerViewFactory(
-//     'html-view',
-//     (int viewId) => html.IFrameElement()
-//       ..width = '100%'
-//       ..height = '100%'
-//       ..srcdoc = r"""
-// """
-//       ..style.border = 'none',
-//   );
- 
-//   void _displayEmailsFromFolder(String folder) async {
-//     Map<String, List<SerializableMessage>> messagesMap = {};
+class _EmailPageState extends State<EmailPage> {
+  final ApiService apiService = ApiService();
+  List<GetThreadResponse> emails = [];
 
-//     try {
-//       var url = Uri.http(
-//           '127.0.0.1:3001', 'sorted_threads_by_date', {'folder': folder});
-//       var response = await http.get(url);
+  // Function to handle folder selection
+  void _onFolderSelected(String folder) async {
+    List<GetThreadResponse> fetchedEmails = await apiService.fetchEmailsFromFolder(folder, 0);
+    setState(() {
+      emails = fetchedEmails;
+    });
+  }
 
-//       Map<String, dynamic> json = jsonDecode(response.body);
-
-//       json.forEach((key, value) {
-//         List<SerializableMessage> messages = (value as List)
-//             .map((item) => SerializableMessage.fromJson(item))
-//             .toList();
-//         messagesMap[key] = messages;
-//       });
-//     } catch (e) {
-//       print('_displayEmailsFromFolder caught error: $e');
-//     }
-//     setState(() {
-//       emails.clear();
-//       emails = messagesMap.values.toList().expand((list) => list).toList();
-//       ;
-//     });
-//   }
-
-//   Future<List<Widget>> _getDrawerItems() async {
-//     List<String> drawerItems = [];
-
-//     try {
-//       var url = Uri.http('127.0.0.1:3001', 'folders');
-//       var response = await http.get(url);
-//       drawerItems = List<String>.from(json.decode(response.body));
-//     } catch (e) {
-//       print('_getDrawerItems caught error: $e');
-//     }
-
-//     List<Widget> drawerWidgets = [];
-
-//     for (String item in drawerItems) {
-//       drawerWidgets.add(
-//         ListTile(
-//           leading: Icon(Icons.mail),
-//           title: Text(item),
-//           onTap: () {
-//             _displayEmailsFromFolder(item);
-//             Navigator.pop(context);
-//           },
-//         ),
-//       );
-//     }
-
-//     return drawerWidgets;
-//   }
-
-//   @override
-//   Widget build(BuildContext context) {
-//     return Scaffold(
-//       appBar: AppBar(
-//         backgroundColor: Theme.of(context).colorScheme.inversePrimary,
-//         title: Text(widget.title),
-//       ),
-//       drawer: Drawer(
-//         child: FutureBuilder<List<Widget>>(
-//           future:
-//               _getDrawerItems(), // call the async function to get the future
-//           builder:
-//               (BuildContext context, AsyncSnapshot<List<Widget>> snapshot) {
-//             if (snapshot.connectionState == ConnectionState.waiting) {
-//               // While data is loading, show a progress indicator
-//               return Center(child: CircularProgressIndicator());
-//             } else if (snapshot.hasError) {
-//               // If something went wrong, show an error message
-//               return Center(child: Text('Error: ${snapshot.error}'));
-//             } else {
-//               // When data is fetched successfully, display the items
-//               return ListView(
-//                 padding: EdgeInsets.zero,
-//                 children:
-//                     snapshot.data!, // Unwrap the data once confirmed it's there
-//               );
-//             }
-//           },
-//         ),
-//       ),
-//       body: EmailListScreen(
-//         emails: emails,
-//       ),
-//     );
-//   }
-// }
-
-// class EmailListScreen extends StatelessWidget {
-//   List emails;
-//   EmailListScreen({required this.emails});
-
-//   @override
-//   Widget build(BuildContext context) {
-//     print(emails);
-//     return Scaffold(
-//       appBar: AppBar(
-//         title: Text('Emails'),
-//       ),
-//       body: ListView.separated(
-//         itemCount: emails.length,
-//         itemBuilder: (context, index) {
-//           return ListTile(
-//               title: Text(emails[index].from,
-//                   style: TextStyle(fontWeight: FontWeight.bold)),
-//               subtitle: Column(
-//                 crossAxisAlignment: CrossAxisAlignment.start,
-//                 children: [
-//                   Text(emails[index].subject),
-//                 ],
-//               ),
-//               trailing: Text(emails[index].date.toString()),
-//               onTap: () {
-//                 Navigator.push(
-//                   context,
-//                   MaterialPageRoute(
-//                       builder: (context) => EmailView(emailContent: "")),
-//                 );
-//               });
-//         },
-//         separatorBuilder: (context, index) {
-//           return Divider();
-//         },
-//       ),
-//     );
-//   }
-// }
-
-// class HtmlContentWidget extends StatelessWidget {
-//   @override
-//   Widget build(BuildContext context) {
-//     return Container(
-//       width: 800,
-//       height: 10000,
-//       child: HtmlElementView(viewType: 'html-view'),
-//     );
-//   }
-// }
-
-// class EmailView extends StatelessWidget {
-//   final String emailContent;
-
-//   EmailView({required this.emailContent});
-
-//   @override
-//   Widget build(BuildContext context) {
-//     return Scaffold(
-//         appBar: AppBar(
-//           title: Text("HTML Content"),
-//         ),
-//         body: Container(
-//           width: 800,
-//           height: 10000,
-//           child: HtmlElementView(
-//             viewType: 'html-view',
-//           ),
-//         )
-
-//         // Text(
-//         //   """
-//         //   <h1>Heading</h1>
-//         //   <p>This is a <strong>simple</strong> HTML example.</p>
-//         //   """,
-//         // ),
-//         );
-//   }r
-// }
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      appBar: AppBar(title: Text('Email Page')),
+      drawer: FolderDrawer(
+        apiService: apiService,
+        onFolderTap: _onFolderSelected,
+      ),
+      body: EmailListScreen(
+        emails: emails,
+        getEmailContent: apiService.fetchEmailContent,
+      ),
+    );
+  }
+}