import React from 'react'
import {Text} from 'react-native';
import DateUtil from "./DateUtil";
import PropTypes from "prop-types";

class Chronometer extends React.Component {


    componentWillMount() {
        this.setState({dataAtual: new Date()});

        setInterval(() => {
                const difference = DateUtil.differenceBetweenTwoDates(this.state.dateStart, this.state.dataAtual);
                //let cronometro = `${difference.days}  ${difference.hours}:${difference.minutes}: ${difference.seconds}`;
                let hours, minutes,seconds;
                hours = this.formatNumberLessThanTen(difference.hours);
                minutes = this.formatNumberLessThanTen(difference.minutes);
                seconds = this.formatNumberLessThanTen(difference.seconds);

                let chronometer = null;
                if(difference.days > 1) {
                    chronometer = `${difference.days} dias ${hours}h ${minutes}m ${seconds}s`;
                } else {
                    chronometer = `${hours}h ${minutes}m ${seconds}s`;
                }
                this.setState({dataAtual: new Date(), difference, chronometer})
            },
            1000)
    }

    formatNumberLessThanTen(number){
        if(number < 10){
            return "0" + number;
        } else {
            return number;
        }
    }

    constructor(props) {
        super(props);
        this.state = {
            dateStart: props.dateStart,
            dataAtual: new Date(),
            difference: {hours: 0, minutes: 0, seconds: 0},
            chronometer: 0
        }
    }

    render() {
        return <Text style={{ fontSize: 20}}> {this.state.chronometer}</Text>
    }
}

Chronometer.propTypes = {
    dateStart: PropTypes.instanceOf(Date)
};

Chronometer.defaultProps = {
    dateStart: new Date()
};

export default Chronometer;