import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import {
	Text,
	StyleSheet,
} from 'react-native';


import Reanimated from 'react-native-reanimated';
import { PanGestureHandler, State } from 'react-native-gesture-handler';

const {
	add,
	block,
	Code,
	call,
	cond,
	eq,
	event,
	set,
	not,
} = Reanimated;

const styles = StyleSheet.create({
	container: {
		position: 'absolute',
		top: 0,
		left: 0,
		borderWidth: 1,
		borderColor: '#00ffaa',
		marginLeft: 10,
		marginTop: 50,
		backgroundColor: '#FFFFFF',
	},
});

export default class Debug extends React.Component {
	static propTypes = {
		info: PropTypes.object.isRequired,
	}

	constructor(props) {
		super(props);
		const infoList = Object.keys(props.info);
		this.stateChangeDebouncer = {};
		const infoListValues = infoList.map((item) => props.info[item]);

		this.changeState = _.throttle((args) => {
			const state = {};
			infoList.forEach((item, index) => {
				state[item] = args[index];
			});
			this.setState(state);
		}, 100, { leading: true, trailing: false });

		this.state = {
			infoList,
		};
		const is = block(call(infoListValues, this.changeState));
		this.listener = () => is;

		this.panOffsetX = new Reanimated.Value(0);
		this.panOffsetY = new Reanimated.Value(0);

		this.translateX = new Reanimated.Value(0);
		this.translateY = new Reanimated.Value(0);

		this.isPanning = new Reanimated.Value(0);

		this.panEvent = event([{
			nativeEvent: ({
				translationX, translationY,
			}) => block([
				cond(this.isPanning, [
					set(this.translateX, add(translationX, this.panOffsetX)),
					set(this.translateY, add(translationY, this.panOffsetY)),
				]),
			]),
		}], {
			useNativeDriver: true,
		});


		this.panChangeState = event([{
			nativeEvent: ({ state }) => block([
				cond(eq(state, State.ACTIVE), [
					cond(not(this.isPanning), [
						set(this.isPanning, 1),
					]),
				], cond(eq(state, State.END), [
					// set(this.translateX, add(translationX, this.panOffsetX)),
					// set(this.translateY, add(translationY, this.panOffsetY)),
					set(this.panOffsetX, this.translateX),
					set(this.panOffsetY, this.translateY),
					set(this.isPanning, 0),
				])),
			]),
		}], {
			useNativeDriver: true,
		});
	}


	render() {
		const { infoList } = this.state;
		return (
			<>
				<Code>{this.listener}</Code>
				<PanGestureHandler
					onGestureEvent={this.panEvent}
					onHandlerStateChange={this.panChangeState}
				>
					<Reanimated.View
						style={[styles.container, { transform: [{ translateX: this.translateX, translateY: this.translateY }] }]}
					>
						{infoList.map((item) => (
							<Text key={` ${item}`}><Text style={{ fontWeight: 'bold' }}>{item}</Text>: {this.state[item]}</Text>
						))}
					</Reanimated.View>
				</PanGestureHandler>
			</>
		);
	}
}
