import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:pm25go/scan.dart';
import 'bluetooth.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pocket PM2.5 Monitor',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: createMaterialColor(Color.fromARGB(255, 64, 155, 253)),
      ),
      home: const MyHomePage(title: 'Pocket PM2.5 Monitor'),
    );
  }
}

MaterialColor createMaterialColor(Color color) {
  List strengths = <double>[.05];
  final swatch = <int, Color>{};
  final int r = color.red, g = color.green, b = color.blue;

  for (int i = 1; i < 10; i++) {
    strengths.add(0.1 * i);
  }
  strengths.forEach((strength) {
    final double ds = 0.5 - strength;
    swatch[(strength * 1000).round()] = Color.fromRGBO(
      r + ((ds < 0 ? r : (255 - r)) * ds).round(),
      g + ((ds < 0 ? g : (255 - g)) * ds).round(),
      b + ((ds < 0 ? b : (255 - b)) * ds).round(),
      1,
    );
  });
  return MaterialColor(color.value, swatch);
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _statusText = "正在等待藍牙運接…\nWaiting for Bluetooth Connection...";

  //Bluetooth Connection
  bool _btConnected = false;
  DeviceSelectionWrapper connectedBluetoothDevice = DeviceSelectionWrapper();

  //Data update for display
  int _pm01 = 0; //No recommended data found
  int _pm25 = 0; //Healthy range: 35, recommend < 15
  int _pm10 = 0; //Healthy range: 150, recommend < 50
  void _toggleBluetooth() async {
    // This call to setState tells the Flutter framework that something has
    // changed in this State, which causes it to rerun the build method below
    // so that the display can reflect the updated values. If we changed
    // _counter without calling setState(), then the build method would not be
    // called again, and so nothing would appear to happen.
    DeviceSelectionWrapper deviceStateToSend = connectedBluetoothDevice;
    final DeviceSelectionWrapper result = await Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) =>
                ConnectionPage(currentState: deviceStateToSend)));
    connectedBluetoothDevice = result;

    //Update the status text
    if (result.deviceSelected && result.deviceConnected) {
      setState(() {
        _statusText = "已連接到藍牙裝置 " + result.deviceName;
      });
    } else {
      setState(() {
        _statusText = "選擇無效或未建立連接";
      });
    }
    return;
  }

  void _connectBluetoothDevice() {
    try {
      _btConnected = true;
    } catch (exception) {
      //Connection to BT failed
      _btConnected = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar:
          null /*AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      )*/
      ,
      body: SingleChildScrollView(
          child: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            //Title banner
            Image.asset('assets/images/banner.png'),
            //Status Text
            Container(
              width: double.infinity,
              padding: const EdgeInsetsDirectional.all(16),
              child: Text(
                _statusText,
                textAlign: TextAlign.left,
              ),
            ),
            //PM 1.0 Display
            Container(
                padding: const EdgeInsetsDirectional.only(
                    start: 16, end: 16, top: 8),
                child: Row(children: <Widget>[
                  Expanded(
                    flex: 2,
                    child: Container(
                        padding: EdgeInsets.all(5),
                        height: 120,
                        color: Colors.blue,
                        child: Text(
                          (() {
                            if (_pm01 == 0) {
                              return "無數據";
                            } else if (_pm01 < 35) {
                              return "良好";
                            }
                            return "一般";
                          }()),
                          style: const TextStyle(color: Colors.white),
                        )),
                  ),
                  Expanded(
                    flex: 8,
                    child: Container(
                        color: Colors.white,
                        height: 120,
                        padding: const EdgeInsetsDirectional.only(top: 30),
                        child: Column(
                          children: [
                            const Text(
                              "PM 1.0 數值",
                              textAlign: TextAlign.center,
                            ),
                            Text(
                              '$_pm01 μg/m^3',
                              textAlign: TextAlign.center,
                              style: const TextStyle(fontSize: 30),
                            )
                          ],
                        )),
                  ),
                ])),

            //PM 2.5 Display
            Container(
                padding: const EdgeInsetsDirectional.only(
                    start: 16, end: 16, top: 8),
                child: Row(children: <Widget>[
                  Expanded(
                    flex: 2,
                    child: Container(
                        padding: EdgeInsets.all(5),
                        height: 120,
                        color: Colors.grey,
                        child: Text(
                          (() {
                            if (_pm25 == 0) {
                              return "無數據";
                            } else if (_pm25 < 15) {
                              return "良好";
                            } else if (_pm25 < 35) {
                              return "一般";
                            }

                            return "差";
                          }()),
                          style: TextStyle(color: Colors.white),
                        )),
                  ),
                  Expanded(
                    flex: 8,
                    child: Container(
                        color: Colors.white,
                        height: 120,
                        padding: EdgeInsetsDirectional.only(top: 30),
                        child: Column(
                          children: [
                            Text(
                              "PM 2.5 數值",
                              textAlign: TextAlign.center,
                            ),
                            Text(
                              '$_pm25 μg/m^3',
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: 30),
                            )
                          ],
                        )),
                  ),
                ])),

            //PM 10 Display
            Container(
                padding: const EdgeInsetsDirectional.only(
                    start: 16, end: 16, top: 8),
                child: Row(children: <Widget>[
                  Expanded(
                    flex: 2,
                    child: Container(
                        padding: EdgeInsets.all(5),
                        height: 120,
                        color: Colors.grey,
                        child: Text(
                          (() {
                            if (_pm10 == 0) {
                              return "無數據";
                            } else if (_pm10 < 50) {
                              return "良好";
                            } else if (_pm10 < 150) {
                              return "一般";
                            }

                            return "差";
                          }()),
                          style: TextStyle(color: Colors.white),
                        )),
                  ),
                  Expanded(
                    flex: 8,
                    child: Container(
                        color: Colors.white,
                        height: 120,
                        padding: EdgeInsetsDirectional.only(top: 30),
                        child: Column(
                          children: [
                            Text(
                              "PM 10.0 數值",
                              textAlign: TextAlign.center,
                            ),
                            Text(
                              '$_pm10 μg/m^3',
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: 30),
                            )
                          ],
                        )),
                  ),
                ])),
          ],
        ),
      )),
      floatingActionButton: FloatingActionButton(
        onPressed: _toggleBluetooth,
        tooltip: '連接藍牙裝置',
        child: const Icon(Icons.bluetooth),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
