
// import 'package:bluetooth_print/bluetooth_print.dart';
// import 'package:bluetooth_print/bluetooth_print_model.dart';
import 'package:esc_pos_bluetooth/esc_pos_bluetooth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';

import 'package:logger/logger.dart';
import 'package:satu/core/models/settings/printer_setting.dart';
import 'package:satu/core/redux/actions/setting_actions.dart';
import 'package:satu/core/redux/store.dart';
import 'package:satu/core/utils/logger.dart';
import 'package:satu/core/utils/pos_printer.dart';
import 'package:satu/widgets/bar/products_app_bar.dart';
import 'package:satu/widgets/bar/products_title_bar.dart';
import 'package:satu/widgets/fields/line_checkbox.dart';

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

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

class _PrinterSelectState extends State<PrinterSelect> {
  final Logger log = getLogger('_PrinterViewState');

  //BluetoothPrint? bluetoothPrint;
  //
  // bool _connected = false;
  // BluetoothDevice? _device;
  PrinterBluetoothManager printerManager = PrinterBluetoothManager();
  List<PrinterBluetooth> _devices = [];

  @override
  void initState() {
    //bluetoothPrint = BluetoothPrint.instance;
    // if (WidgetsBinding.instance != null) {
    //   WidgetsBinding.instance!.addPostFrameCallback((_) => initBluetooth());
    // }

    super.initState();

    printerManager.scanResults.listen((devices) async {
      // print('UI: Devices found ${devices.length}');
      setState(() {
        _devices = devices;
      });
    });
    _startScanDevices();
  }

  void _startScanDevices() {
    setState(() {
      _devices = [];
    });
    printerManager.startScan(Duration(seconds: 4));
  }

  void _stopScanDevices() {
    printerManager.stopScan();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  // Future<void> initBluetooth() async {
  //   bluetoothPrint!.startScan(timeout: const Duration(seconds: 4));
  //
  //   //final bool isConnected = await bluetoothPrint!.isConnected ?? false;
  //
  //   // bluetoothPrint!.state.listen((state) {
  //   //   print('cur device status: $state');
  //   //
  //   //   switch (state) {
  //   //     case BluetoothPrint.CONNECTED:
  //   //       setState(() {
  //   //         _connected = true;
  //   //         tips = 'connect success';
  //   //       });
  //   //       break;
  //   //     case BluetoothPrint.DISCONNECTED:
  //   //       setState(() {
  //   //         _connected = false;
  //   //         tips = 'disconnect success';
  //   //       });
  //   //       break;
  //   //     default:
  //   //       break;
  //   //   }
  //   // });
  //
  //   if (!mounted) return;
  //
  //   // if (isConnected) {
  //   //   setState(() {
  //   //     _connected = true;
  //   //   });
  //   // }
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const ProductsAppBar(
        title: 'Поиск устройства печати',
      ),
      body: SingleChildScrollView(
        child: StoreConnector<AppState, PrinterSetting>(
            converter: (store) => store.state.settingState!.printer!,
            builder: (context, printer) {
              return Column(
                children: <Widget>[
                  const ProductsTitleBarBar(
                      title: 'Выберите устройство печати'),
                  StreamBuilder<List<PrinterBluetooth>>(
                    stream: printerManager.scanResults,
                    initialData: const [],
                    builder: (c, snapshot) => Column(
                      children: (snapshot.data ?? [])
                          .map(
                            (d) => Column(
                              children: [
                                LineCheckBox(
                                  d.name ?? '',
                                  value: printer.device != null &&
                                      printer.device!.address == d.address,
                                  onTap: () => {
                                    Redux.store!.dispatch(
                                      selectBluetoothDevice(
                                        bluetoothDeviceToPrinterDevice(d),
                                      ),
                                    )
                                  },
                                ),
                                const Divider(
                                  height: 1,
                                ),
                              ],
                            ),
                          )
                          .toList(),
                    ),
                  ),
                ],
              );
            }),
      ),
    );
  }
}
