import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';

const String port = "8443";
const String serverURI = "https://127.0.0.1:$port/";
const String mapEndpoint = "update_map";
// NB: if http connection fails, run: adb reverse tcp:8443 tcp:8443
const int fetchInterval = 5;

void main() {
  runApp(const App());
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: DefaultPage(),
    );
  }
}

// fetchData requests data from the update_map endpoint
Future<void> fetchData() async {
  try {
    // Custom HTTP client
    HttpClient client = HttpClient()
      ..badCertificateCallback = // NB: temporary disable SSL certificate validation
          (X509Certificate cert, String host, int port) => true;

    var request =  await client.getUrl(Uri.parse(serverURI+mapEndpoint));
    var response = await request.close();

    print('Response status: ${response.statusCode}');
  } catch (e) {
    print('Failed to connect to the server: $e');
  }
}

class DefaultPage extends StatefulWidget {
  const DefaultPage({Key? key}) : super(key: key);

  @override
  _DefaultPageState createState() => _DefaultPageState();
}

class _DefaultPageState extends State<DefaultPage> {
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    // Call fetchData when the widget is first created
    fetchData();

    // Schedule fetchData to run periodically based on fetchInterval const
    const Duration fiveMinutes = Duration(minutes: fetchInterval);
    _timer = Timer.periodic(fiveMinutes, (timer) {
      fetchData();
    });
  }

  @override
  void dispose() {
    // Cancel timer on widget termination
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double boxWidth = 0.8;
    double boxHeight = 1.2; 

    return Scaffold(
      appBar: AppBar(
        title: const Text('IceMap'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              width: screenWidth * boxWidth,
              height: screenWidth * boxHeight,
              color: Colors.blue, // Set the color of the box
            ),
            SizedBox(height: 20), // Spacing between box and text
            Text(
              'Default page',
              style: TextStyle(fontSize: 24),
            ),
          ],
        ),
      ),
    );
  }
}