import IDUtil from '../../../util/IDUtil';

import PropTypes from 'prop-types';
import DatePicker from 'react-datepicker';
import { Link } from 'react-router-dom';
import moment from "moment";

/**
* Shows the data entry form and handles saving the data entry using the given api.
*/
class DataEntryForm extends React.PureComponent {

    constructor(props) {
        super(props);

        this.titleRef = React.createRef();
        this.descriptionRef = React.createRef();
        this.creatorRef = React.createRef();
        this.fileUrlRef = React.createRef();

        let dateCreated = null;
        if(this.props.dataEntry.dateCreated){
            let tzOffset = moment(this.props.dataEntry.dateCreated).utcOffset();
            dateCreated = moment(this.props.dataEntry.dateCreated).add(parseInt(tzOffset), 'minutes').toDate();
        }

        this.state = {
            validationError: false,
            dateCreated: dateCreated
        };
        this.CLASS_PREFIX = 'def';
    }

    handleSubmit = () => {
        const dataEntry = Object.assign({}, this.props.dataEntry);
        dataEntry.title = this.titleRef.current.value;
        dataEntry.descr = this.descriptionRef.current.value;
        dataEntry.dateCreated = this.state.dateCreated;
        dataEntry.creator = this.creatorRef.current.value;
        dataEntry.fileUrl = this.fileUrlRef.current.value;
        dataEntry.id = this.props.dataEntry.id;
        this.save(dataEntry);

        return false;
    };

    isFilledIn = fieldRefs => fieldRefs.every(fr => fr.current !== null && fr.current.value.length !== 0);

    validUrl = url => /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/.test(url);

    validateForm = e => {
        e.preventDefault();//TODO check if this desired or not
        if(this.isFilledIn([this.titleRef, this.fileUrlRef]) && this.validUrl(this.fileUrlRef.current.value)) {
            this.handleSubmit();
        } else {
            this.setState({
                validationError: true
            })
        }
    };

    onDateChanged = date => {
        let dateCreated = null;
        if (date) {
            let tzOffset = moment(date).utcOffset();
            dateCreated = moment(date).add(parseInt(tzOffset), "minutes");
        }
        if(dateCreated) {
            dateCreated = dateCreated.toDate();
            this.setState({dateCreated: dateCreated});
        }
    };


    //Save the data entry using the Collection API
    save(dataEntry, collectionId, callback) {
        this.props.api.saveEntry(this.props.user.id, this.props.collectionId, dataEntry, entry => {
            if (entry && entry.id) {
                this.props.dataEntryDidSave(entry);
            } else {
                alert('An error occured while saving this entry');
            }
        });
    }

    cancelEditing = () => this.props.onCancelEditing ? this.props.onCancelEditing() : void(0);

    renderErrorMessage = msg => <div className={IDUtil.cssClassName('validation-error', this.CLASS_PREFIX)}>{msg}</div>;

    render() {
        const errorMessage = this.state.validationError ? this.renderErrorMessage('Please provide a title and a valid media file url') : null;

        return (
            <form className={IDUtil.cssClassName('data-entry-form')} onSubmit={this.validateForm}>
                <div>
                    <label className="label">Title</label>
                    <input
                        type="text"
                        name="name"
                        defaultValue={this.props.dataEntry.title}
                        ref={this.titleRef}/>
                    <label className="label">Description</label>
                    <textarea
                        name="description"
                        defaultValue={this.props.dataEntry.descr}
                        ref={this.descriptionRef}/>
                    <label className="label">Date created</label>
                    <DatePicker
                        selected={this.state.dateCreated}
                        value={this.state.dateCreated}
                        openToDate={this.state.dateCreated}
                        onChange={this.onDateChanged}
                        showMonthDropdown={true}
                        showYearDropdown={true}
                        dropdownMode="select"
                        className="form-control"
                        placeholderText="Pick a date"
                        dateFormat="dd/MM/yyyy"
                    />
                    <label className="label">Creator</label>
                    <input
                        type="text"
                        name="creator"
                        defaultValue={this.props.dataEntry.creator}
                        ref={this.creatorRef}/>
                    <label className="label">URL to media file</label>
                    <input
                        type="text"
                        name="fileUrl"
                        defaultValue={this.props.dataEntry.fileUrl}
                        id="fileUrl"
                        ref={this.fileUrlRef}/>
                </div>
                {errorMessage}
                <div className="actions">
                    <a onClick={this.cancelEditing} className="btn">Cancel</a>
                    <input type="submit" className="btn primary add" value={this.props.submitButton}/>
                </div>
            </form>
        )
    }
}

DataEntryForm.PropTypes = {
    submitButton: PropTypes.string.isRequired,
    cancelLink: PropTypes.string.isRequired,
    dataEntry: PropTypes.shape({
        title: PropTypes.string.isRequired,
        descr: PropTypes.string.isRequired
    }).isRequired,
    entryDidSave: PropTypes.func.isRequired,
    user: PropTypes.shape({
        id: PropTypes.string.isRequired
    }),
    collectionId: PropTypes.string.isRequired,
    api: PropTypes.shape({
        saveEntry: PropTypes.func.isRequired
    })
};

export default DataEntryForm;
