
import React, { Component } from 'react';
import { FlatList, SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Button } from 'react-native-paper';

import { INPrinterScanControllerCallback, NPrinter, NPrinterScanController } from 'react-native-nemonic-sdk';
import AsyncStorage from '@react-native-async-storage/async-storage';

class SelectPrinterScreen extends Component implements INPrinterScanControllerCallback {

    private printerScanController: NPrinterScanController

    constructor(props: {}) {
        super(props)
        this.state = {
            selectedPrinterName: 'No selected printer',
            printers: [] as NPrinter[]
        }

        this.printerScanController = new NPrinterScanController(this)
        this.printerScanController.startScan()
    }

    render(): React.ReactNode {
        return (
            <SafeAreaView style={styles.container}>
                {this.getSelectedPrinterView()}
                {this.getPrintersView()}
                {this.getRefreshView()}
            </SafeAreaView>
        );
    }

    componentDidMount(): void {
        this.updateSelectedPrinter()
        this.setState({
            printers: [] as NPrinter[]
        })
    }

    componentDidUpdate(): void {
        this.updateSelectedPrinter()
    }

    componentWillUnmount(): void {
        this.printerScanController.stopScan()
    }

    private async updateSelectedPrinter() {
        var name = await AsyncStorage.getItem('selectedPrinterName') ?? ''
        var macAddress = await AsyncStorage.getItem('selectedPrinterMacAddress') ?? ''

        if (name.trim().length == 0) {
            this.setState({
                selectedPrinterName: 'No selected printer'
            })
        }
        else {
            this.setState({
                selectedPrinterName: name + '(' + macAddress + ')'
            })
        }
    }

    private getSelectedPrinterView(): React.JSX.Element {
        return (<Text style={styles.rowStretch && styles.textBold}>{this.state.selectedPrinterName}</Text>);
    }

    private getPrintersView(): React.JSX.Element {
        return (
            <FlatList
                data={this.state.printers}
                renderItem={({ item }) =>
                    <TouchableOpacity
                        onPress={() => this.selectPrinter(item)}
                        style={item.getName() + '(' + item.getMacAddress() + ')' === this.state.selectedPrinterName ? styles.textSelected : styles.text}
                    >
                        <Text style={styles.text}>{item.getName()}({item.getMacAddress()})</Text>
                    </TouchableOpacity>
                }
            />
        );
    }

    private selectPrinter(printer: NPrinter) {
        var name = printer.getName();
        var macAddress = printer.getMacAddress();
        var type = printer.getType();

        this.setState({
            selectedPrinterName: printer.getName() + '(' + printer.getMacAddress() + ')'
        })
        AsyncStorage.setItem('selectedPrinterName', name);
        AsyncStorage.setItem('selectedPrinterMacAddress', macAddress);
        AsyncStorage.setItem('selectedPrinterType', type.toString());
    }

    private getRefreshView(): React.JSX.Element {
        return (
            <Button
                style={styles.refreshButton}
                onPress={() => {
                    this.printerScanController.stopScan();
                    this.setState({
                        printers: []
                    });
                    this.printerScanController.startScan();
                }}>
                Refresh
            </Button>);
    }

    public deviceFound(printer: NPrinter): void {
        this.setState({
            printers: [...this.state.printers, printer]
        });
    }
}

export default SelectPrinterScreen;

// type PrinterText = {
//     name: string,
//     macAddress: string,
//     type: number
// };

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    row: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    column: {
        flexDirection: 'column',
        flexWrap: 'wrap'
    },
    rowStretch: {
        flexDirection: 'row',
        alignSelf: 'stretch',
        alignItems: 'stretch',
        alignContent: 'stretch'
    },
    text: {
        textAlign: 'center',
        textAlignVertical: 'center',
        fontSize: 18,
        height: 50,
    },
    textSelected: {
        textAlign: 'center',
        textAlignVertical: 'center',
        fontSize: 18,
        height: 50,
        backgroundColor: 'lightblue'
    },
    textBold: {
        textAlign: 'center',
        textAlignVertical: 'center',
        fontSize: 20,
        fontWeight: 'bold',
        height: 50,
        backgroundColor: 'lightgray',
    },
    refreshButton: {
        position: 'absolute',
        alignSelf: 'center',
        bottom: 16
    }
});