import 'dart:convert'; import 'package:crab_ui/api_service.dart'; import 'package:crab_ui/home_page.dart'; import 'package:flutter/material.dart'; // import 'package:flutter_widget_from_html/flutter_widget_from_html.dart'; import 'package:http/http.dart' as http; // import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter/services.dart' show rootBundle; class AuthService { Future isUserLoggedIn() async { try { final response = await http.get(Uri.parse('http://localhost:6823/read-config')); print(response.statusCode); print(response.body); if (response.statusCode == 200) { final data = jsonDecode(response.body); // return data['config']; try { var url = Uri.http('${data['ip']}:${data['port']}', 'is_logged_in'); var response = await http.get(url); print(response.body); if (response.statusCode == 200) { print('all good in the east!'); String jsonOuter = jsonDecode(response.body); Map json = jsonDecode(jsonOuter); // print(json["is_logged_in"]); ApiService.ip = data['ip']; ApiService.port = data['port']; return json["is_logged_in"]; } } catch (er) { print(er); } } } catch (e) { print(e); } return false; } Future readConfFile() async { final content = await rootBundle.loadString('/crabmail.conf'); return content; } Map parseConfFile(String content) { final Map config = {}; final lines = content.split('\n'); for (var line in lines) { line = line.trim(); if (line.isEmpty || line.startsWith('#')) continue; final parts = line.split('='); if (parts.length == 2) { final key = parts[0].trim(); final value = parts[1].trim(); config[key] = value; } } return config; } Future loginUser(String email, String password) async { try {} catch (e) {} return false; } } class LoginPage extends StatefulWidget { const LoginPage({super.key}); @override _LoginPageState createState() => _LoginPageState(); } class SplashScreen extends StatefulWidget { @override _SplashScreenState createState() => _SplashScreenState(); } class _SplashScreenState extends State { final AuthService _authService = AuthService(); @override void initState() { super.initState(); _checkLoginStatus(); } Future _checkLoginStatus() async { // SharedPreferences prefs = await SharedPreferences.getInstance(); // print(prefs); // bool isLoggedIn = prefs.getBool('isLoggedIn') ?? false; bool isLoggedIn = await _authService.isUserLoggedIn(); print("is loogeed in $isLoggedIn"); if (isLoggedIn) { Navigator.pushReplacementNamed(context, '/home'); } else { Navigator.pushReplacementNamed(context, '/login'); } } @override Widget build(BuildContext context) { return Center( child: Scaffold( body: Center(child: CircularProgressIndicator()), ), ); } } class _LoginPageState extends State { final AuthService _authService = AuthService(); // Controllers for capturing user input final TextEditingController _ipController = TextEditingController(); final TextEditingController _portController = TextEditingController(); final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); // final ConfigManager _configManager = // ConfigManager("${Directory.current.parent}../crabmail2.conf"); // Key to identify the form final _formKey = GlobalKey(); Future setIp(String ip) async { // _configManager.setField("api_addr", ip); return false; } Future setPort(String port) async { return false; } Future login() async { bool result = await _handleLogin(); if (result) { Navigator.pushReplacementNamed(context, '/home'); } } // Future _checkConfiguration() async { // return false; // } // void checkLogin() async { // try { // var url = Uri.http('127.0.0.1:3001', 'is_logged_in'); // var response = await http.get(url); // print(response.body); // if (response.statusCode == 200) { // print('all good on the west'); // } // } catch (e) { // print(e); // } // // bool isLoggedIn = await _authService.isUserLoggedIn(); // } // Function to handle login action Future _handleLogin() async { if (_formKey.currentState!.validate()) { // Perform login action (e.g., authenticate with backend) String ip = _ipController.text; String port = _portController.text; String email = _emailController.text; String password = _passwordController.text; // For demonstration, just print the values print('Email: $email'); print('Password: $password'); print(ip); print(port); String baseUrl = "http://$ip:$port"; print("baseurl " + baseUrl); print(baseUrl); try { final response = await http.get(Uri.parse('http://localhost:6823/read-config')); print(response.statusCode); print(response.body); if (response.statusCode == 200) { final data = jsonDecode(response.body); // return data['config']; } } catch (e) { print("caught in catch"); print(e); return false; } Map updates = { // "username": email, // "password": password, "ip": ip, "port": port, }; print("past"); try { final sending = await http.post( Uri.parse('http://localhost:6823/update-config'), headers: {'Content-Type': "application/json"}, body: jsonEncode(updates)); print("sending"); } catch (e) { print(e); return false; } try { // String status = await http.post(Uri.parse('')) var url_log = Uri.http('$ip:$port', 'log_in'); Map filteredData = { "email": email, "password": password, // 'email': updates['username'], // 'password': updates['password'] }; print(filteredData); var status = await http.post( url_log, headers: { 'Content-Type': 'application/json', }, body: jsonEncode(filteredData), ); if (status.statusCode == 200) { print('response status ${status.body}'); if (status.body == "Successful log in") { ApiService.ip = ip; ApiService.port = port; return true; } } } catch (e) { print(e); return false; } print("after"); return false; // final content = await _authService.readConfFile(); // final config = await _authService.parseConfFile(content); // print("BASE URL ${config["base_url"]}"); // print("api address ${config["api_addr"]}"); // print(config); // const url = '' // Clear the input fields // _ipController.clear(); // _portController.clear(); // _emailController.clear(); // _passwordController.clear(); } return false; } @override Widget build(BuildContext context) { // try { // _configManager.loadConfig(); // print(_configManager.getField('base_url')); // } catch (e) { // print("broke at build $e"); // } // _configManager. return Center( child: Scaffold( appBar: AppBar( title: const Text('Login Page'), ), body: Center( child: SingleChildScrollView( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Align( alignment: Alignment.center, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Sign in to your email'), SizedBox( height: 5, ), Container( width: 200, child: TextFormField( controller: _ipController, decoration: const InputDecoration( labelText: "IP", hintText: 'Enter your IP for the backend', helperMaxLines: 1, ), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your ip'; } }, // onSaved: (value) async { // final content = await _authService.readConfFile(); // final config = // await _authService.parseConfFile(content); // print("BASE URL ${config["base_url"]}"); // print("api address ${config["api_addr"]}"); // //TODO: call a function to set the field ip in conf // }, ), ), Container( width: 200, child: TextFormField( controller: _portController, decoration: const InputDecoration( labelText: "Port", hintText: 'Enter the port', helperMaxLines: 1, ), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your port'; } return null; }, onSaved: (value) { //TODO: call a function to set the field port in conf }, ), ), // Email Field Container( width: 200, child: TextFormField( controller: _emailController, decoration: const InputDecoration( labelText: 'Email', hintText: 'Enter your email', helperMaxLines: 1, ), validator: (value) { // Simple email validation if (value == null || value.isEmpty) { return 'Please enter your email'; } if (!RegExp(r'^\S+@\S+\.\S+$').hasMatch(value)) { // print(value); return 'Please enter a valid email address'; } return null; }, ), ), const SizedBox(height: 16.0), // Password Field Container( width: 200, child: TextFormField( controller: _passwordController, decoration: const InputDecoration( labelText: 'Password', hintText: 'Enter your password', ), obscureText: true, // Hide the password text autofillHints: null, validator: (value) { // Simple password validation if (value == null || value.isEmpty) { return 'Please enter your password'; } if (value.length < 6) { return 'Password must be at least 6 characters long'; } return null; }, ), ), const SizedBox(height: 32.0), // Login Button SizedBox( width: 200, child: ElevatedButton( onPressed: login, child: const Text('Login'), ), ), // SizedBox( // width: 200, // child: ElevatedButton( // // onPressed: checkLogin, // onPressed: () async { // await _authService.isUserLoggedIn(); // // print(result); // }, // child: const Text('checker'), // ), // ) ], ), ), ), ), ), ), ); } }