import React, {ReactElement, useEffect, useState} from 'react'; import {Text, View} from 'react-native'; // @ts-ignore import Barcode from 'react-native-barcode-builder'; import {Button} from 'react-native-paper'; import {BarCodeProps, ButtonProps, PrintingProps} from '../models/ElementProps'; import {colors, styles} from './Styles'; import AsyncStorage from '@react-native-community/async-storage'; import * as Print from 'expo-print'; enum PrintStatus { SAVING = 'SAVING', PRINTING = 'PRINTING', DONE = 'DONE', } const _renderBarCodeRects = (props: PrintingProps): string => { const dataStr = _propsToDataString(props); const rects: string[] = []; // TODO: set base width from label width in pixels // 2 inches = 190 pixels // for now, just guesstimate. const baseWidth = 7; for (let i = 0; i < dataStr.length; i++) { // TODO: Convert dataStr to barcode rectangles with x, y, width, height // barcodejs library has some useful stuff? // Or maybe somehow use something in the guts of react-native-barcode-builder? // For now, just put in some dummy x values and widths. rects.push(``); } return rects.join(' ') } const _propsToDataString = (props: BarCodeProps): string => { return `${props.id}-${props.date.getTime()}-${props.location}`; } const _save = (props: PrintingProps): Promise => { const storageKey = _propsToDataString(props); const storageVal = { id: props.id, date: props.date, location: props.location, }; return AsyncStorage.setItem(storageKey, JSON.stringify(storageVal)); } const _print = (props: PrintingProps): Promise => { const dataStr = _propsToDataString(props); return Print.printAsync({ html: ` ID#: ${props.id} Date: ${props.date.toLocaleDateString()} ${props.date.toLocaleTimeString()} Loc#: ${props.location} ${_renderBarCodeRects(props)} ${dataStr} `, }); } export const PrintButton = (props: ButtonProps): ReactElement => { return Print Labels; } export const PrintingMessage = (props: PrintingProps): ReactElement => { const [statusStr, setStatusStr] = useState('Saving data...'); const [printStatus, setPrintStatus] = useState(PrintStatus.SAVING); useEffect(() => { _save(props).finally(() => { setPrintStatus(PrintStatus.PRINTING); setStatusStr('Data saved. Printing...') _print(props).finally(() => { setPrintStatus(PrintStatus.DONE); setStatusStr('Data sent to printer.'); }); }); }, []); const RetryButton = (): ReactElement | null => { if (printStatus === PrintStatus.DONE) { return _print(props)} color={colors.onBackground} style={styles.btnLg} labelStyle={styles.btnLg} >Print again } else { return null; } } return {statusStr} {printStatus === PrintStatus.DONE ? 'Done' : 'Cancel'} ; } export const BarCodeDisplay = (props: BarCodeProps): ReactElement => { const data = _propsToDataString(props); return ID#: {props.id} Date: {props.date.toLocaleDateString()}, {props.date.toLocaleTimeString()} Location {props.location} ; }
ID#: ${props.id}
Date: ${props.date.toLocaleDateString()} ${props.date.toLocaleTimeString()}
Loc#: ${props.location}
${dataStr}