import '../../../shim.js';
import crypto from 'crypto';
import _ from 'lodash';
import React from 'react';
import QRCode from 'react-native-qrcode-generator';
import {
	View,
	Dimensions,
	Alert,
	Text,
} from 'react-native';
import { connect } from 'react-redux';
import { color } from 'nixplay-ui-kit';
import { BluetoothEscposPrinter, BluetoothManager } from 'react-native-bluetooth-escpos-printer';
import PropTypes from 'prop-types';
// import i18n from '~/locale/i18n';

import { color as basicColor } from '~/styles/variables'

const ENCRYPTION_KEY = "MAAGAppDataCollectionAndDelivery"; // Must be 256 bits (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16

const { width: screenWidth } = Dimensions.get('window');

const styles = {
	container: {
		backgroundColor: color.white,
		flex: 1,
	},
	sectionHeader: {
		paddingVertical: 5,
		paddingHorizontal: 20,
		backgroundColor: color.blue,
	},
	listDetail: {
		marginVertical: 5,
		paddingHorizontal: 20,
	},
	mainBg: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'center',
		paddingHorizontal: 18,
		marginVertical: 50,
	},
};

class ShowQRCode extends React.Component {
	// eslint-disable-next-line react/sort-comp
	static navigationOptions = ({ navigation }) => {
		const { getParam } = navigation;
		return {
			title: 'QR Code',
			headerTransparent: false,
			hideBackButton: false,
			leftButtons: [],
			rightButtons: [{
				onPress: () => { getParam('onScanPrinter')(); },
				icon: 'print',
			}],
		};
	}

	static propTypes = {
		navigation: PropTypes.object.isRequired,
	}

	constructor(props) {
		super(props);

/**
					firstName,
					lastName,
					middleName,
					age,
					dob,
					programID,
					remarks,
					idNumber,
					region,
					province,
					municipality,
					barangay,
					cRegion,
					cProvince,
					cMunicipality,
					cBarangay,
					suffix,
					sex,
					ethnicity,
					occupation,
					sector,
					monthlyIncome,
					education,
					houseOwnership,
					healthCondition,
					program,
					nationalId,
					reliefAssistance,
					volunteerName: fullName,
					volunteerMob: mobileNumber,
					dateCreated: epochtime,
					beneficiaryMobile,
					emailAddress,
					avatarPhoto,
 */

		const data = this.props.navigation.getParam('data', {});
		// console.log('DATA: ', data);
		// const memberId = crypto.randomBytes(10).toString('hex').toUpperCase();
		// console.log('RANDOM BYTES: ', memberId);
		const {
			firstName, lastName, middleName, dob, cBarangay, municipality, sex, memberRefId, beneficiaryMobile, emailAddress,
		} = data;
		// console.log('beneficiaryMobile: ', beneficiaryMobile);
		// console.log('email: ', emailAddress);
		// console.log('username: ', username);
		const myUserName = (!_.isEmpty(beneficiaryMobile)) ? beneficiaryMobile : emailAddress;
		const myMiddleName = (!_.isEmpty(middleName)) ? middleName.charAt(0).toUpperCase() : '';
		const fullName = `${firstName.toUpperCase()} ${myMiddleName} ${lastName.toUpperCase()}`.split(' ').join('_');
		// barangay
		const { brgyCode } = cBarangay;
		// municipality
		const { citymunCode } = municipality;
		// province
		// const { provCode, provDesc } = province;
		// const formattedBarangay = (!_.isEmpty(brgyCode)) ? `${brgyCode}:${brgyDesc}` : '';
		const formattedSex = (!_.isEmpty(sex)) ? sex.toUpperCase().charAt(0) : '';
		const formattedDOB = (!_.isEmpty(dob)) ? dob.split('-').join('') : '';
		const formattedUsername = (!_.isEmpty(myUserName)) ? myUserName.replace('+63', '') : '';
		// const rawData = `${fullName}|${formattedUsername}|${memberRefId}|${formattedDOB}|${age}|${formattedSex}|${formattedBarangay}|${citymunCode}:${citymunDesc}|${provCode}:${provDesc}|${regType}`;
		const rawDataPrint = `${memberRefId}.${fullName}.${formattedUsername}.${formattedDOB}.${formattedSex}.${brgyCode}.${citymunCode}`;
		// console.log('RAWPRINT: ', rawDataPrint);
		// console.log('RAW: ', rawData);
		// const proposeUserRefKey = this.encrypt(rawData);
		const userKeyPrint = this.encrypt(rawDataPrint);

		// console.log('DECRYPTED: ', this.decrypt('3c5c54dc484f91766974b42b7b3171dd:5aeaa2a79964854881e8c8f0bf0707730e1e440e5d2674ade4ae2e59b9d0f2cdf754025ef2ae3b8454d573b9f0ad15b135471146ba1796889d4816b7c1ee6075'));
		// console.log('DECRYPTED: ', this.decrypt('f6af2be1fb3eddbef082e429b4f647aa:220a17057a2e3f4e62eefbbb8a9509f7b8dd3100a6975eeb263133713bfa9a61f40e2a7172be460f8f37350dac06b6787177b1598869a81b6aedf86889d917e708e64b9836e80c6a7e2c7e1bf070cf03276d2b309ac11f1c2bad1c079882bf83ef82d322c4313588b6461948c328e147'));

		// console.log('KEY: ', proposeUserRefKey);
		// console.log('QRKEY: ', userKeyPrint);

		this.state = {
			// devices: null,
			pairedDs: [],
			foundDs: [],
			// bleOpend: false,
			// loading: true,
			// boundAddress: '',
			// debugMsg: '',
			// name: '',
			userKeyPrint,
			memberRefId,
			fullName: fullName.toUpperCase(),
			status: 'Updated QR, Ready for Print',
		};
		this.props.navigation.setParams({
			onScanPrinter: this.onScanPrinter,
		});
	}

	componentDidMount() {
		// BluetoothManager.isBluetoothEnabled().then((enabled) => {
		// 	this.showAlert(
		// 		'MAAGApp - BLE',
		// 		`STATUS: ${enabled}`,
		// 		() => { },
		// 		() => { },
		// 	);
		// }, (e) => {
		// });

		// if (Platform.OS === 'ios') {
		// 	// let bluetoothManagerEmitter = new NativeEventEmitter(BluetoothManager);
		// 	// this.listeners.push(bluetoothManagerEmitter.addListener(
		// 	// 	BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED,
		// 	// 	(rsp)=> {
		// 	// 		this._deviceAlreadPaired(rsp)
		// 	// 	}));
		// 	// this.listeners.push(bluetoothManagerEmitter.addListener(BluetoothManager.EVENT_DEVICE_FOUND, (rsp)=> {
		// 	// 	this._deviceFoundEvent(rsp)
		// 	// }));
		// 	// this.listeners.push(bluetoothManagerEmitter.addListener(BluetoothManager.EVENT_CONNECTION_LOST, ()=> {
		// 	// 	this.setState({
		// 	// 		name: '',
		// 	// 		boundAddress: ''
		// 	// 	});
		// 	// }));
		// } else if (Platform.OS === 'android') {
		// 	this.listeners.push(DeviceEventEmitter.addListener(BluetoothManager.EVENT_DEVICE_ALREADY_PAIRED, (rsp) => {
		// 		this.deviceAlreadPaired(rsp);
		// 	}));
		// this.listeners.push(DeviceEventEmitter.addListener(BluetoothManager.EVENT_DEVICE_FOUND, (rsp) => {
		// 	this.deviceFoundEvent(rsp);
		// }));
		// 	this.listeners.push(DeviceEventEmitter.addListener(BluetoothManager.EVENT_CONNECTION_LOST, () => {
		// 	}));
		// 	this.listeners.push(DeviceEventEmitter.addListener(BluetoothManager.EVENT_BLUETOOTH_NOT_SUPPORT, () => {
		// 		ToastAndroid.show('Device Not Support Bluetooth !', ToastAndroid.LONG);
		// 	}));
		// }
	}

	onScanPrinter = () => {
		this.scan();
	}

	deviceAlreadPaired(rsp) {
		let ds = null;
		if (typeof (rsp.devices) === 'object') {
			ds = rsp.devices;
		} else {
			try {
				ds = JSON.parse(rsp.devices);
			} catch (e) {
				// ignore
			}
		}
		if (ds && ds.length) {
			let pared = this.state.pairedDs;
			pared = pared.concat(ds || []);
			this.setState({ pairedDs: pared });
		}
	}

	deviceFoundEvent(rsp) {
		let r = null;
		try {
			if (typeof (rsp.device) === 'object') {
				r = rsp.device;
			} else {
				r = JSON.parse(rsp.device);
			}
		} catch (e) { // alert(e.message);
			// ignore
		}
		// alert('f')
		if (r) {
			const found = this.state.foundDs || [];
			if (found.findIndex) {
				const duplicated = found.findIndex((x) => x.address === r.address);
				// CHECK DEPLICATED HERE...
				if (duplicated === -1) {
					found.push(r);
					this.setState({ foundDs: found });
				}
			}
		}
	}

	scan() {
		const datetime = (new Date()).toLocaleString();
		this.setState({ status: 'Ready scanning printer nearby..' });
		BluetoothManager.scanDevices()
			.then((s) => {
				try {
					const { found, paired } = JSON.parse(s);
					const itemList = [...paired, found];
					itemList.forEach((BLE) => {
						if (BLE.address && (_.isEqual(BLE.name, 'PT200') || (BLE.name.indexOf('MPT')) === 0 || (BLE.name.indexOf('MTP')) === 0)) {
							this.setState({ status: `Found printer ${BLE.address}-${BLE.name}` });
							// auto connect
							BluetoothManager.connect(BLE.address)
								.then(async () => {
									this.setState({ status: 'Now print QR code..' });
									await BluetoothEscposPrinter.printerAlign(BluetoothEscposPrinter.ALIGN.CENTER);
									await BluetoothEscposPrinter.printText('MAAGApp - www.maag.app\r\n', {});
									await BluetoothEscposPrinter.printQRCode(
										this.state.userKeyPrint.toString(),
										400,
										BluetoothEscposPrinter.ERROR_CORRECTION.L,
									);
									await BluetoothEscposPrinter.printText(`\r\nDATE#: ${datetime}\n`, {});
									await BluetoothEscposPrinter.printText(`NAME#: ${this.state.fullName}\r\n`, {});
									await BluetoothEscposPrinter.printText('\r\n\r\n', {});
									this.setState({ status: 'Done print QR code..' });
									await BluetoothManager.disconnect(BLE.address)
										.then(() => {
											this.setState({ status: 'Done Printing!' });
											this.showAlert(
												'MAAGApp - BLE Print',
												`Done Printing QR Code - ${this.state.memberRefId} - ${datetime}`,
												() => { },
												() => { },
											);
										});
								}, () => {
									// this.setState({ loading:false });
								});
						}
					});
				} catch (e) {
					this.setState({ status: 'ERROR Printing! CODE2' });
					console.log('Error: ', e);
				}
			}, (er) => {
				// this.setState({ loading: false });
				this.setState({ status: 'ERROR Printing! CODE1' });
				console.log('Error: ', er);
			});
	}

	showAlert = (title, msg, callbackCancel, callbackContinue) => {
		Alert.alert(
			title,
			msg,
			[
				{
					text: 'Cancel',
					onPress: callbackCancel ? () => { callbackCancel(); } :
						() => {},
				},
				{
					text: 'Continue',
					onPress: callbackContinue ? () => { callbackContinue(); } :
						() => {},
				},
			],
			{ cancelable: false },
		);
	}

	encrypt = (text) => {
		const iv = crypto.randomBytes(IV_LENGTH);
		const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
		let encrypted = cipher.update(text);

		encrypted = Buffer.concat([encrypted, cipher.final()]);

		return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
	}

	decrypt = (text) => {
		const textParts = text.split(':');
		const iv = Buffer.from(textParts.shift(), 'hex');
		const encryptedText = Buffer.from(textParts.join(':'), 'hex');
		const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(ENCRYPTION_KEY), iv);
		let decrypted = decipher.update(encryptedText);

		decrypted = Buffer.concat([decrypted, decipher.final()]);

		return decrypted.toString();
	}


	render() {
		return (
			<View style={styles.container}>
				<View style={[styles.mainBg]}>
					<QRCode
						value={this.state.userKeyPrint}
						size={(screenWidth - 28)}
						bgColor={basicColor.wrikeBg}
						fgColor="white"
					/>
				</View>
				<Text style={{ alignSelf: 'center', marginBottom: 10 }} >{this.state.status}</Text>
			</View>
		);
	}
}


export { ShowQRCode };
export default connect(null, null)(ShowQRCode);
