import {Text, View} from "react-native";
import BasicButton from "../../components/BasicButton/BasicButton";
import {useScanningContext} from "../../providers/ScanProvider";
import printingApi from "../../api/printingApi";
import {convertPdfToBitmaps} from "../../connectors/PdfToBitmap";
import TcpSocket from 'react-native-tcp-socket';
import {Zpl} from "react-native-zpl-code";

async function generateZplCodes(images: string[]) {
    const zplCodes = [];

    for (const image of images) {
        const zplBuilder = new Zpl.Builder();
        zplBuilder.setup({
            size: {
                heightDots: 320, // 40mm at 203 DPI
                widthDots: 464,  // 58mm at 203 DPI
            },
            labelHome: {
                x: 0,
                y: 0,
            },
            labelTop: 0,
            labeShift: 0,
            orientation: "NORMAL",
            media: {
                type: "MARK_SENSING",
                dots: 0,
            },
        });

        zplBuilder.image({
            uri: `data:image/png;base64,${image}`,
            x: 0,
            y: 0,
            width: 464,
            height: 320,
            dither: true,
        });

        const zplCode = await zplBuilder.build();
        zplCodes.push(zplCode);
    }

    return zplCodes;
}

function MoneyScreen() {
    const {scan} = useScanningContext();
    const a = "123";
    const onPress = () => {
        printingApi.getLabel(386618).then(async result => {
            const images = await convertPdfToBitmaps(result);
            const client = TcpSocket.createConnection(
                {
                    host: "192.168.1.69",
                    port: 9100,
                },
                () => {
                    console.log('Connected')
                    generateZplCodes(images).then(codes => {
                        console.log('Generated codes')
                        codes.forEach((code, idx) => {
                            console.log(`Printing ${idx}`)
                            client.write(code)
                        })
                        console.log('Ending')
                        client.end();
                        // client.destroy();
                        console.log('Disconnected')

                    })

                },
            );
            client.on("error", error => {
                console.log("Error:", error);
            });

            // Handle connection close
            client.on("close", () => {
                console.log("Connection closed");
            });

        });
    }
    return (
        <View>
            <Text style={{fontSize: 36}}>Money</Text>
            <BasicButton onPress={() => onPress()} label={"test"}/>
        </View>
    )
}

export default MoneyScreen;