import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:aman_kassa_flutter/redux/constants/setting_const.dart';
import 'package:charset_converter/charset_converter.dart';
import 'package:esc_pos_utils/esc_pos_utils.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as Im;
import 'package:path_provider/path_provider.dart';
import 'package:qr_flutter/qr_flutter.dart';

Future<Ticket> testTicket(PaperSize paper) async {
  final Ticket ticket = Ticket(paper);

  //Uint8List encTxt11 = await CharsetConverter.encode("cp866", "Russian: Привет Мир!");
  //ticket.textEncoded(encTxt11, styles: PosStyles(codeTable: PosCodeTable.pc866_2));
  //ticket.textEncoded(encTxt11);

  // ticket.text('Special 1: àÀ', styles: PosStyles(codeTable: PosCodeTable.westEur)); //А
  // ticket.text('Special 1: á'.toUpperCase(), styles: PosStyles(codeTable: PosCodeTable.westEur));// Б
  // ticket.text('Special 1: â', styles: PosStyles(codeTable: PosCodeTable.westEur)); //В
  // ticket.text('Special 1: ã', styles: PosStyles(codeTable: PosCodeTable.westEur));// Г
  // ticket.text('Special 1: äÄ', styles: PosStyles(codeTable: PosCodeTable.westEur)); //Д
  // ticket.text('Special 1: å', styles: PosStyles(codeTable: PosCodeTable.westEur));// Е
  // ticket.text('Special 1: æÆ', styles: PosStyles(codeTable: PosCodeTable.westEur));// Ж
  // ticket.text('Special 1: ç', styles: PosStyles(codeTable: PosCodeTable.westEur));//З
  // ticket.text('Special 1: èÈ', styles: PosStyles(codeTable: PosCodeTable.westEur)); // И
  // ticket.text('Special 1: éÉ', styles: PosStyles(codeTable: PosCodeTable.westEur)); // Й
  // ticket.text('Special 1: ê', styles: PosStyles(codeTable: PosCodeTable.westEur));//К
  // ticket.text('Special 1: ëË', styles: PosStyles(codeTable: PosCodeTable.westEur));  // Л
  // ticket.text('Special 1: ìÌ', styles: PosStyles(codeTable: PosCodeTable.westEur));// M
  // ticket.text('Special 1: íÍ', styles: PosStyles(codeTable: PosCodeTable.westEur)); // Н
  // ticket.text('Special 1: î', styles: PosStyles(codeTable: PosCodeTable.westEur));// О
  // ticket.text('Special 1: ï', styles: PosStyles(codeTable: PosCodeTable.westEur)); // П
  // ticket.text('Special 1: ð', styles: PosStyles(codeTable: PosCodeTable.westEur));// Р
  // ticket.text('Special 1: ñ', styles: PosStyles(codeTable: PosCodeTable.westEur));// С
  // ticket.text('Special 1: ò', styles: PosStyles(codeTable: PosCodeTable.westEur)); // Т
  // ticket.text('Special 1: óÓ', styles: PosStyles(codeTable: PosCodeTable.westEur)); //У
  // ticket.text('Special 1: ô', styles: PosStyles(codeTable: PosCodeTable.westEur));// Ф
  // ticket.text('Special 1: õÕ', styles: PosStyles(codeTable: PosCodeTable.westEur));// Х
  // ticket.text('Special 1: ö', styles: PosStyles(codeTable: PosCodeTable.westEur)); //Ц
  // ticket.text('Special 1: ÷', styles: PosStyles(codeTable: PosCodeTable.westEur)); //Ч
  // ticket.text('Special 1: ø', styles: PosStyles(codeTable: PosCodeTable.westEur));//Ш
  // ticket.text('Special 1: ù', styles: PosStyles(codeTable: PosCodeTable.westEur)); //Щ
  // ticket.text('Special 1: ú', styles: PosStyles(codeTable: PosCodeTable.westEur));//Ъ
  // ticket.text('Special 1: û', styles: PosStyles(codeTable: PosCodeTable.westEur));//Ы
  // ticket.text('Special 1: üÜ', styles: PosStyles(codeTable: PosCodeTable.westEur)); //Ь
  // ticket.text('Special 1: ý', styles: PosStyles(codeTable: PosCodeTable.westEur)); //Э
  // ticket.text('Special 1: þ', styles: PosStyles(codeTable: PosCodeTable.westEur)); // ю
  // ticket.text('Special 1: ÿß', styles: PosStyles(codeTable: PosCodeTable.westEur)); //Я

  // Uint8List encTxt11 = await CharsetConverter.encode("cp866", "Russian: Привет Мир!");
  // //ticket.textEncoded(encTxt11, styles: PosStyles(codeTable: PosCodeTable.pc866_2));
  // ticket.textEncoded(encTxt11);

  ticket.text(
      'Regular: aA bB cC dD eE fF gG hH iI jJ kK lL mM nN oO pP qQ rR sS tT uU vV wW xX yY zZ');
  //ticket.text('Special 1: àÀ èÈ éÉ ûÛ üÜ çÇ ôÔ', styles: PosStyles(codeTable: PosCodeTable.westEur));
  //ticket.text('Special 2: blåbærgrød', styles: PosStyles(codeTable: PosCodeTable.westEur));

  ticket.text('Bold text', styles: PosStyles(bold: true));
  ticket.text('Reverse text', styles: PosStyles(reverse: true));
  ticket.text('Underlined text',
      styles: PosStyles(underline: true), linesAfter: 1);
  ticket.text('Align left', styles: PosStyles(align: PosAlign.left));
  ticket.text('Align center', styles: PosStyles(align: PosAlign.center));
  ticket.text('Align right',
      styles: PosStyles(align: PosAlign.right), linesAfter: 1);

  ticket.row([
    PosColumn(
      text: 'col3',
      width: 3,
      styles: PosStyles(align: PosAlign.center, underline: true),
    ),
    PosColumn(
      text: 'col6',
      width: 6,
      styles: PosStyles(align: PosAlign.center, underline: true),
    ),
    PosColumn(
      text: 'col3',
      width: 3,
      styles: PosStyles(align: PosAlign.center, underline: true),
    ),
  ]);

  ticket.text('Text size 200%',
      styles: PosStyles(
        height: PosTextSize.size2,
        width: PosTextSize.size2,
      ));

  // Print image
  //final ByteData data = await rootBundle.load('assets/images/logo.png');
  //final Uint8List bytes = data.buffer.asUint8List();
  // Print image using alternative commands
  // ticket.imageRaster(image);
  // ticket.imageRaster(image, imageFn: PosImageFn.graphics);

  // Print barcode
  final List<int> barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4];
  ticket.barcode(Barcode.upcA(barData));



  ticket.feed(2);

  ticket.cut();
  return ticket;
}

Future<Ticket> testTicketImage(PaperSize paper) async {
  final Ticket ticket = Ticket(paper);

  // Print image
  final ByteData byteData = await rootBundle.load('assets/images/check.png');
  final Uint8List bytes = byteData.buffer.asUint8List();
  final Im.Image image = Im.decodeImage(bytes);
  // Using `ESC *`
  //ticket.image(imagea);
  // Using `GS v 0` (obsolete)
  //ticket.imageRaster(imagea);
  // Using `GS ( L`
  ticket.imageRaster(image, imageFn: PosImageFn.bitImageRaster);
  //ticket.image(imagea);


  ticket.feed(2);

  ticket.cut();
  return ticket;
}

Future<Ticket> printImageCheck(PaperSize paper, String base64Src) async {
  final Ticket ticket = Ticket(paper);
  final Uint8List bytes = base64Decode(base64Src);
  final Im.Image image = Im.decodeImage(bytes);
  ticket.imageRaster(image, imageFn: PosImageFn.bitImageRaster);
  //ticket.image(image);
  ticket.feed(2);
  ticket.cut();
  return ticket;
}


Future<Ticket> printTextCheck(PaperSize paper, String encoding, var data ) async {
  final Ticket ticket = Ticket(paper);
  ticket.emptyLines(1);


  PosCodeTable codeTable;
  if(encoding == SettingPrinterEncodingCp866) {
    codeTable = PosCodeTable.pc866_2;
  } else if(encoding == SettingPrinterEncodingWin1251) {
    codeTable = PosCodeTable.wpc1251;
  }

  //ticket.setGlobalCodeTable(codeTable);
  ticket.setGlobalFont(PosFontType.fontB);


  String qr = data['qr'];


  List<dynamic> rows =  data['rows'] as List;
  for(dynamic element in rows) {
    var text = element['text'];
    int size = element['size'] as int;
    bool center = element['center'] !=null ? element['center'] as bool : false;
    if(text is List) {
      Uint8List firstCol = await CharsetConverter.encode(encoding, (text).first as String);
      Uint8List lastCol = await CharsetConverter.encode(encoding, (text).last as String);
      ticket.row([
        PosColumn(
          textEncoded: firstCol,
          width: 6,
          styles: PosStyles(align: PosAlign.left, codeTable: codeTable ),
        ),
        PosColumn(
          textEncoded: lastCol,
          width: 6,
          styles: PosStyles(align: PosAlign.right, codeTable: codeTable ),
        ),
      ]);
    } else {
      String line = text as String;
      if(line == 'breakline') {
        ticket.hr();
      } else if(line == 'br') {
        ticket.emptyLines(1);
      } else if(line.trim() == '') {
        ticket.emptyLines(1);
      } else {
        line = line.replaceAll("«", '\"');
        line = line.replaceAll("»", '\"');
        Uint8List encTxt11 = await CharsetConverter.encode(encoding, line);
        ticket.textEncoded( encTxt11, styles: PosStyles( align: center ? PosAlign.center : PosAlign.left, codeTable: codeTable  ));
      }
    }
  }

  // Print barcode
  //final List<int> barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4];
  //ticket.barcode(Barcode.upcA(barData));
  //ticket.qrcode(qr, align: PosAlign.center);
  ticket.emptyLines(1);
  const double qrSize = 200;
  try {
    final uiImg = await QrPainter(
      data: qr,
      version: QrVersions.auto,
      gapless: true,
    ).toImageData(qrSize);
    //final dir = await getTemporaryDirectory();
    //final pathName = '${dir.path}/qr_tmp.png';
    //final qrFile = File(pathName);
    //final imgFile = await qrFile.writeAsBytes(uiImg.buffer.asUint8List());
    final img = Im.decodePng(uiImg.buffer.asUint8List());
    ticket.image(img);

    //ticket.qrcode(qr, size: QRSize.Size1 );
  } catch (e) {
    print(e);
  }


  ticket.emptyLines(1);
  ticket.feed(1);

  ticket.cut();
  return ticket;
}