
import 'package:esc_pos_bluetooth/esc_pos_bluetooth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:satu/core/models/settings/printer_setting.dart';
import 'package:satu/core/redux/store.dart';
import 'package:satu/core/services/dialog_service.dart';
import 'package:satu/core/services/navigator_service.dart';
import 'package:satu/core/utils/locator.dart';
import 'package:satu/core/utils/pos_printer.dart';
import 'package:satu/routes/route_names.dart';
import 'package:satu/shared/app_colors.dart';
import 'package:satu/shared/ui_helpers.dart';
import 'package:satu/widgets/bar/products_app_bar.dart';
import 'package:satu/widgets/fields/line_tile.dart';

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

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

class _PrinterViewState extends State<PrinterView> {
  final NavigatorService _navigatorService = locator<NavigatorService>();
  final DialogService _dialogService = locator<DialogService>();
  PrinterBluetoothManager printerManager = PrinterBluetoothManager();

  bool printerLocked = false;

  @override
  void initState() {
    super.initState();
  }

  void print() async {
    setState(() {
      printerLocked = true;
    });
    try {
      PrinterSetting printerSetting = Redux.store!.state.settingState!.printer!;
      printerManager.selectPrinter(
        PrinterBluetooth(
          printerDeviceToBluetoothDevice(printerSetting.device!),
        ),
      );
      final int chunkSizeBytes = getChunkSize();
      final int queueSleepTimeMs = getQueueSleep();

      List<int> data = List.empty();
      if (PrinterConst.encodingBigEncoding == printerSetting.encoding) {
        data = await getTestReceiptImg(
          printerSetting.paperSize!,
        );
      } else {
        data = await getTestReceipt(
          printerSetting.encoding!,
          printerSetting.paperSize!,
        );
      }

      final PosPrintResult printResult = await printerManager.writeBytes(
        data,
        chunkSizeBytes: chunkSizeBytes,
        queueSleepTimeMs: queueSleepTimeMs,
      );
      if (printResult.value != 1) {
        _dialogService.showDialog(description: printResult.msg);
      }
    } finally {
      await Future.delayed(const Duration(seconds: 7));
      setState(() {
        printerLocked = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: ProductsAppBar(
        title: 'Принтер',
        actions: [
          StoreConnector<AppState, PrinterSetting>(
            converter: (store) => store.state.settingState!.printer!,
            builder: (context, snapshot) {
              final bool success =
                  snapshot.device != null && printerLocked == false;
              return IconButton(
                onPressed: success ? print : null,
                icon: Icon(
                  Icons.print,
                  color: success ? textColor : placeholderColor,
                ),
              );
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: StoreConnector<AppState, PrinterSetting>(
          converter: (store) => store.state.settingState!.printer!,
          builder: (context, printer) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                verticalSpaceSmall,
                LineTile(
                  printer.device?.name ?? 'Устройство не выбрано',
                  onTap: () {
                    _navigatorService
                        .push(settingPrinterBluetoothSelectViewRoute);
                  },
                  labelText: 'Устройство печати',
                ),
                verticalSpaceSmall,
                LineTile(
                  printer.paperSize ?? 'Размер не указан',
                  onTap: () {
                    _navigatorService.push(settingPrinterPaperSizeViewRoute);
                  },
                  labelText: 'Размер чека',
                ),
                verticalSpaceSmall,
                LineTile(
                  printer.encoding ?? 'Кодировка не указана',
                  onTap: () {
                    _navigatorService.push(settingPrinterEncodingViewRoute);
                  },
                  labelText: 'Кодировка печати',
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
