import TextInput from '../text-input/text-input.jsx';
import Ajax from 'dd/lib/ajax';
import '../text-input/text-input.less';

let USZipFormatter;

/* istanbul ignore else: no one cares */
if (typeof document !== 'undefined') {
    USZipFormatter = require('../../etc/us-zip-formatter').default;
}


/**\

    title: PostalCode
    category: atom
    description: Grabs city and state info from a zip code input
    props:
        placeholder[String]: see TextInput
        altPlaceholder[String]: see TextInput
        match[Function]:
            A callback for when a successful match is made.
        failed[Function]:
            A callback for when no match was found. If the server does not
            respond within 500 ms, this cb will be called.

\**/
class PostalCode extends TextInput {
    static validate(zip) {
        return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zip);
    }

    static defaultProps = {
        placeholder: 'Zip Code',
        altPlaceholder: '00000'
    };

    update(evt) {
        super.update(evt);

        if (this.request) {
            this.request.abort();
        }

        if (typeof this.props.match !== 'function' ||
            !PostalCode.validate(evt.value())) {
            return;
        }

        this.request = Ajax({
            url: `//api.zippopotam.us/US/${evt.value()}`,
            success: (data) => {
                if (!data || !data.hasOwnProperty('places')) {
                    return;
                }

                const place = {
                    city: data.places[0]['place name'],
                    state: data.places[0]['state abbreviation']
                };

                clearTimeout(this.timeout);
                this.props.match(place);
            },
            error: () => {
                if (typeof this.props.failed === 'function') {
                    this.props.failed();
                }
            }
        });

        this.timeout = setTimeout(() => {
            /* istanbul ignore else: no one cares */
            if (this.request) {
                this.request.abort();
            }
        }, 500);
    }

    getFormatter() {
        return new USZipFormatter();
    }
}

export default PostalCode;
