import 'package:flutter/material.dart';

import 'package:cx_1500n_plugin/cx_1500n_plugin.dart';

void main() {
  runApp(MaterialApp(home: const MyApp(),debugShowCheckedModeBanner: false,));
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _cx1500nPlugin = Cx1500nPlugin();
  String debugData = "Logs will be here";
  bool isConnected = false;
  int power = 5;
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _cx1500nPlugin.events.listen((event) {
      print("event received: $event");
      setState(() {
        debugData += "\n\n$event";
      });
    });


  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              Image.asset("images/header.png"),
              SizedBox(height: 16.0),
              Text("Identium flutter Plugin - CX1500N",style: TextStyle(fontSize: 18.0),),
              SizedBox(height: 16.0),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Container(
                          height: 250,
                          width: double.infinity,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            color: Colors.black12,
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: Scrollbar(
                              controller: _scrollController,
                              thumbVisibility: true,
                              child: SingleChildScrollView(
                                controller: _scrollController,
                                child: Text(
                                  debugData,
                                  style:
                                      TextStyle(color: Colors.black, fontSize: 18.0),
                                  textAlign: TextAlign.start,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                      ElevatedButton(
                        onPressed: !isConnected ? _connect : null,
                        child: Text("Connect"),
                      ),
                      SizedBox(height: 8),
                      ElevatedButton(
                        onPressed: isConnected ? _disconnect : null,
                        child: Text("Disconnect"),
                      ),
                      SizedBox(height: 8),
                
                      // enventory
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        spacing: 8.0,
                        children: [
                          ElevatedButton(
                            onPressed: isConnected ? _startInventory : null,
                            child: Text("Start Inventory"),
                          ),
                          SizedBox(height: 8),
                          ElevatedButton(
                            onPressed: isConnected ? _stopInventory : null,
                            child: Text("Stop Inventory"),
                          ),
                        ],
                      ),
                      SizedBox(height: 8),
                
                      //set power
                      ElevatedButton(
                        onPressed: isConnected ? _setPower : null,
                        child: Text("Set Power"),
                      ),
                
                      SizedBox(height: 8),
                
                      //read
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        spacing: 8.0,
                        children: [
                          ElevatedButton(
                            onPressed: isConnected
                                ? () {
                                    _read(0);
                                  }
                                : null,
                            child: Text("Read Reserved"),
                          ),
                          SizedBox(height: 8),
                          ElevatedButton(
                            onPressed: isConnected
                                ? () {
                                    _read(1);
                                  }
                                : null,
                            child: Text("Read EPC"),
                          ),
                        ],
                      ),
                      SizedBox(height: 8),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        spacing: 8.0,
                        children: [
                          ElevatedButton(
                            onPressed: isConnected
                                ? () {
                                    _read(2);
                                  }
                                : null,
                            child: Text("Read TID"),
                          ),
                          SizedBox(height: 8),
                          ElevatedButton(
                            onPressed: isConnected
                                ? () {
                                    _read(3);
                                  }
                                : null,
                            child: Text("Read User Mem"),
                          ),
                        ],
                      ),
                
                      SizedBox(height: 8),
                      ElevatedButton(
                        onPressed: isConnected
                            ? () {
                                startScan();
                              }
                            : null,
                        child: Text("Scan"),
                      ),
                      // Row(
                      //   mainAxisAlignment: MainAxisAlignment.center,
                      //   spacing: 8.0,
                      //   children: [
                      //     ElevatedButton(
                      //       onPressed: isConnected
                      //           ? () {
                      //               startScan();
                      //             }
                      //           : null,
                      //       child: Text("Start Scan"),
                      //     ),
                      //     SizedBox(height: 8),
                      //     ElevatedButton(
                      //       onPressed: isConnected
                      //           ? () {
                      //               stopScan();
                      //             }
                      //           : null,
                      //       child: Text("Stop Scan"),
                      //     ),
                      //   ],
                      // ),
                      // Container(height: 300.0,color: Colors.amber,)
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );
  }

  void _connect() {
    _cx1500nPlugin.connect().then((s) {
      setState(() {
        isConnected = true;
      });
    }).catchError((e) {
      print("error while connect :: $e");
      setState(() {
        isConnected = false;
        debugData += "\n\n$e";
      });
    });
  }

  void _disconnect() {
    _cx1500nPlugin.disconnect().then((s) {
      setState(() {
        isConnected = false;
      });
    }).catchError((e) {
      print("disconect error  => $e");
      setState(() {
        debugData += "\n\n$e";
      });
    });
  }

  void _startInventory() {
    _cx1500nPlugin.startInventory().then((s) {}).catchError((e) {
      print("_startInventory error  => $e");
      setState(() {
        debugData += "\n\n$e";
      });
    });
  }

  void _stopInventory() {
    _cx1500nPlugin.stopInventory().then((s) {
      setState(() {
        debugData += "\n\n$s";
      });
    }).catchError((e) {
      print("_stopInventory error  => $e");
      setState(() {
        debugData += "\n\n$e";
      });
    });
  }

  void startScan() {
    _cx1500nPlugin.startScan().catchError((e) {
      print("startScan error  => $e");
      setState(() {
        debugData += "\n\n$e";
      });
    });
  }

  void stopScan() {
    _cx1500nPlugin.stopScan().catchError((e) {
      print("stopScan error  => $e");
      setState(() {
        debugData += "\n\n$e";
      });
    });
  }

  void _setPower() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        int tempPower = power; // local state for dialog

        return StatefulBuilder(
          builder: (context, setStateDialog) {
            return Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.0),
              ),
              elevation: 5.0,
              backgroundColor: Colors.white,
              child: Container(
                padding: EdgeInsets.all(20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('Select power'),
                    SizedBox(height: 8),
                    Slider(
                      value: tempPower.toDouble(),
                      min: 5.0,
                      max: 33.0,
                      divisions: 28,
                      label: '$tempPower',
                      onChanged: (double newValue) {
                        setStateDialog(() {
                          tempPower = newValue.round();
                        });
                      },
                    ),
                    Row(
                      children: [
                        Spacer(),
                        ElevatedButton(
                            onPressed: () {
                              setState(() {
                                power = tempPower;
                              });
                              Navigator.pop(context); // close dialog

                              _cx1500nPlugin
                                  .setPower(power)
                                  .then((s) {})
                                  .catchError((e) {
                                print("_setPower error  => $e");
                                setState(() {
                                  debugData += "\n\n$e";
                                });
                              });
                            },
                            child: Text("Set Power"))
                      ],
                    )
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

//0：保留区  1：epc  2:tid   3：UER
  void _read(int memBank) {
    _cx1500nPlugin.read(memBank).then((s) {
      setState(() {
        debugData += "\n\n$s";
      });
    }).catchError((e) {
      print("_read error  => $e");
      setState(() {
        debugData += "\n\n$e";
      });
    });
  }
}
