import React, {Component} from 'react';
import { Image, StyleSheet } from 'react-native';
import ReactCardFlip from 'react-card-flip';

import Popup from "../Popup";

type CardProps = {
    front: any,
    back: any,
    isFlipped: boolean,
    title: string,
    info: string,
    special: string,
    value: string,
    count: string
}

type CardState = {
    front: any,
    back: any,
    isFlipped: boolean
    modelIsOpen: boolean
}


export default class Card extends Component<CardProps, CardState> {

    constructor(props: CardProps) {
        super(props);
        this.state={
            front: "",
            back: "",
            isFlipped: false,
            modelIsOpen: false
        }
        this.handleClick = this.handleClick.bind(this);
    }


    handleClick(e: any) {
        e.preventDefault();
        this.setState(prevState => ({ isFlipped: !prevState.isFlipped }));
    }

    convertBlobToBase64 (blob: Blob) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader;
            reader.onerror = reject;
            reader.onload = () => {
                resolve(reader.result);
            };
            reader.readAsDataURL(blob);
        });
    }

    getToken() {
        const tokenString = localStorage.getItem('token');
        // @ts-ignore
        const userToken = JSON.parse(tokenString);
        return userToken?.token
    };

    componentWillMount(){
        this.setState({
            isFlipped: this.props.isFlipped
        })
        let self = this;
        fetch(this.props.front, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${this.getToken()}`
            }
        })
        .then(response => response.blob())
        .then(this.convertBlobToBase64)
        .then(base64  => {
            // @ts-ignore
            self.setState({
                front: base64
            })
        })

        fetch(this.props.back, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${this.getToken()}`
            }
        })
            .then(response => response.blob())
            .then(this.convertBlobToBase64)
            .then(base64  => {
                // @ts-ignore
                self.setState({
                    back: base64
                })
            })
    }
    openPopup() {
        this.setState({modelIsOpen: true});
    }

    closePopup() {
        this.setState({modelIsOpen: false});
    }

    render() {
        const styles = StyleSheet.create({
            card: {
                width: 116,
                height: 178,
            }
        });

        const stylesPopup = StyleSheet.create({
            card: {
                width: 116,
                height: 178,
                positon: 'relative',
                float: 'left',
            }
        });

        let {front, back, isFlipped} = this.state

        return (
            <div className="card-wrapper">
                <div onClick={this.openPopup.bind(this)}>
                    <ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal" flipSpeedBackToFront={0.4} flipSpeedFrontToBack={0.4}>
                        <div onMouseEnter={this.handleClick} >
                            <Image source={{uri: front}} style={styles.card} />
                        </div>
                        <div onMouseLeave={this.handleClick}>
                            <Image source={{uri: back}} style={styles.card} />
                        </div>
                    </ReactCardFlip>
                </div>
                {this.state.modelIsOpen &&
                <Popup handleClose={this.closePopup.bind(this)}>
                    <h1>{this.props.title}</h1>
                    <p><i>{this.props.count}</i></p>
                    <Image source={{uri: front}} style={stylesPopup.card} />
                    <Image source={{uri: back}} style={stylesPopup.card} />
                    <div className="cardInfo">
                        <p><b>Info:</b> {this.props.info}</p>
                        <p><b>Special:</b> {this.props.special}</p>
                        <p><b>Scoring:</b> {this.props.value} point(s)</p>
                    </div>
                </Popup>
                }
            </div>
        )
    }
}
