import 'package:aman_kassa_flutter/core/locator.dart';
import 'package:aman_kassa_flutter/core/logger.dart';
import 'package:aman_kassa_flutter/core/services/blue_print_service.dart';
import 'package:aman_kassa_flutter/redux/actions/setting_actions.dart';
import 'package:aman_kassa_flutter/redux/store.dart';
import 'package:aman_kassa_flutter/core/models/bluetooth_device.dart';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' hide Image;
import 'package:flutter/rendering.dart';

import 'package:logger/logger.dart';

class PrinterSelectView extends StatefulWidget {
  PrinterSelectView({Key? key, this.title}) : super(key: key);
  final String? title;

  @override
  _PrinterSelectViewState createState() => _PrinterSelectViewState();

}

class _PrinterSelectViewState extends State<PrinterSelectView> {
  BluePrintService printerManager = locator<BluePrintService>();
  List<BluetoothDevice> _devices = [];
  Logger _logger = getLogger('PrinterSelectView');

  @override
  void initState() {
    super.initState();
    printerManager.scanResult.listen((devices) async {
      setState(() {
        _devices = devices;
      });
    });
    _startScanDevices();
  }

  void _startScanDevices() {
    setState(() {
      _devices = [];
    });
    printerManager.scan();
  }

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

  void _selectPrinter(BluetoothDevice printer, BuildContext context, ) async {
    printerManager.device = printer;
    _logger.i(printer.name);
    _logger.i(printer.address);

    BluetoothDevice device = new BluetoothDevice()
      ..address = printer.address
      ..name=printer.name
      ..type=printer.type;

    await Redux.store!.dispatch(selectPrinterFromSetting(device));
    Navigator.of(context).pop(false);
  }
  final key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: key,
      child: Scaffold(
        appBar: AppBar(
          title: Text('Выберите принтер'),
        ),
        body: ListView.builder(
            itemCount: _devices.length,
            itemBuilder: (BuildContext _, int index) {
              return InkWell(
                onTap: () => _selectPrinter(_devices[index], context),
                child: Column(
                  children: <Widget>[
                    Container(
                      height: 60,
                      padding: EdgeInsets.only(left: 10),
                      alignment: Alignment.centerLeft,
                      child: Row(
                        children: <Widget>[
                          Icon(Icons.print),
                          SizedBox(width: 10),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text(_devices[index].name ?? ''),
                                Text(_devices[index].address ?? ''),
                                Text(
                                  'Click to print a test receipt',
                                  style: TextStyle(color: Colors.grey[700]),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    Divider(),
                  ],
                ),
              );
            }),
        floatingActionButton: StreamBuilder<bool>(
          stream: printerManager.isScanning,
          initialData: false,
          builder: (c, snapshot) {
            if (snapshot.data != null) {
              return FloatingActionButton(
                child: Icon(Icons.stop),
                onPressed: _stopScanDevices,
                backgroundColor: Colors.red,
              );
            } else {
              return FloatingActionButton(
                child: Icon(Icons.search),
                onPressed: _startScanDevices,
              );
            }
          },
        ),
      ),
    );
  }

}