'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _getIterator2 = require('babel-runtime/core-js/get-iterator');

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _libphonenumberJs = require('libphonenumber-js');

var _inputFormat = require('input-format');

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _reactResponsiveUi = require('./react-responsive-ui');

var _countryNames = require('./country names');

var _countryNames2 = _interopRequireDefault(_countryNames);

var _internationalIcon = require('./international icon');

var _internationalIcon2 = _interopRequireDefault(_internationalIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// Generate default country options list
var country_options = _countryNames2.default.map(function (_ref) {
	var _ref2 = (0, _slicedToArray3.default)(_ref, 2);

	var value = _ref2[0];
	var label = _ref2[1];
	return {
		value: value.toUpperCase(),
		label: label
	};
});

// Not importing here directly from `react-responsive-ui` npm package
// just to reduce the overall bundle size.

var Input = function (_Component) {
	(0, _inherits3.default)(Input, _Component);

	function Input(props) {
		(0, _classCallCheck3.default)(this, Input);

		// If the default country is set, then populate it
		var _this = (0, _possibleConstructorReturn3.default)(this, (Input.__proto__ || (0, _getPrototypeOf2.default)(Input)).call(this, props));

		_this.state = {};
		_this.state.country_code = props.country;

		if (props.value) {
			_this.state.value = _this.correct_initial_value_if_neccessary(props.value, props.country);
		}

		// Set country option icons (national flags)
		// for those option list items
		// which don't have an icon set.
		var _iteratorNormalCompletion = true;
		var _didIteratorError = false;
		var _iteratorError = undefined;

		try {
			for (var _iterator = (0, _getIterator3.default)(props.countries), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
				var country_option = _step.value;

				if (!country_option.icon) {
					country_option.icon = _react2.default.createElement('img', { className: 'react-phone-number-input__icon', src: '' + props.flagsPath + country_option.value.toLowerCase() + '.svg' });
				}
			}
		} catch (err) {
			_didIteratorError = true;
			_iteratorError = err;
		} finally {
			try {
				if (!_iteratorNormalCompletion && _iterator.return) {
					_iterator.return();
				}
			} finally {
				if (_didIteratorError) {
					throw _iteratorError;
				}
			}
		}

		_this.on_key_down = _this.on_key_down.bind(_this);
		_this.on_change = _this.on_change.bind(_this);
		_this.set_country = _this.set_country.bind(_this);
		_this.parse = _this.parse.bind(_this);
		_this.format = _this.format.bind(_this);
		return _this;
	}

	// If the country code is specified
	//   If the value has a leading plus sign
	//     If it converts into a valid national number for this country
	//       Then the value is set to be that national number
	//     Else
	//       The leading + sign is trimmed
	//   Else
	//     The value stays as it is
	// Else
	//   If the value has a leading plus sign
	//     The value stays as it is
	//   Else
	//     The plus sign is prepended
	//


	(0, _createClass3.default)(Input, [{
		key: 'correct_initial_value_if_neccessary',
		value: function correct_initial_value_if_neccessary(value, country_code) {
			if (!value) {
				return;
			}

			if (country_code) {
				if (value[0] === '+') {
					var parsed = (0, _libphonenumberJs.parse)(value);

					if (parsed.country === country_code) {
						return this.format(parsed.phone, country_code).text;
					} else {
						return value.slice(1);
					}
				}
			} else {
				if (value[0] !== '+') {
					return '+' + value;
				}
			}

			return value;
		}
	}, {
		key: 'set_country',
		value: function set_country(country_code) {
			var previous_country_code = this.state.country_code;

			if (country_code === '-') {
				country_code = undefined;
			}

			this.setState({ country_code: country_code });

			var value = this.state.value;

			// If switching to a country from International
			//   If the international number belongs to this country
			//     Convert it to a national number
			//   Else
			//     Trim the leading + sign
			//
			// If switching to a country from a country
			//   If the value has a leading + sign
			//     If the international number belongs to this country
			//       Convert it to a national number
			//     Else
			//       Trim the leading + sign
			//   Else
			//     The value stays as it is
			//
			// If switching to International from a country
			//   If the value has a leading + sign
			//     The value stays as it is
			//   Else
			//     Take the international plaintext value

			if (value) {
				if (!previous_country_code && country_code) {
					// The value is international plaintext
					var parsed = (0, _libphonenumberJs.parse)(value);

					// If it's for this country,
					// then convert it to a national number
					if (parsed.country === country_code) {
						value = this.format(parsed.phone, country_code).text;
					}
					// Else just trim the + sign
					else {
							value = value.slice(1);
						}
				}

				if (previous_country_code && country_code) {
					if (value[0] === '+') {
						var _parsed = (0, _libphonenumberJs.parse)(value);

						if (_parsed.country === country_code) {
							value = this.format(_parsed.phone, country_code).text;
						} else {
							value = value.slice(1);
						}
					}
				}

				if (previous_country_code && !country_code) {
					if (value[0] !== '+') {
						value = (0, _libphonenumberJs.format)(parse_national_number(value, previous_country_code), previous_country_code, 'International_plaintext');
					}
				}

				this.on_change(value, country_code);
			}

			// Focus the phone number input upon country selection
			// (do it in a timeout because of autocomplete's own focus timeout)
			_reactDom2.default.findDOMNode(this.input).focus();
		}
	}, {
		key: 'parse',
		value: function parse(character, value) {
			if (character === '+') {
				// Only leading '+' is allowed
				if (!value) {
					return character;
				}
			}
			// Allow digits
			else if (character >= '0' && character <= '9') {
					return character;
				}
		}
	}, {
		key: 'format',
		value: function format(value) {
			var country_code = arguments.length <= 1 || arguments[1] === undefined ? this.state.country_code : arguments[1];

			// `value` is already parsed input, i.e.
			// either International plaintext phone number
			// or just local phone number digits.

			// "As you type" formatter
			var formatter = new _libphonenumberJs.as_you_type(country_code);

			// Is used to check if a country code can already be derived
			this.formatter = formatter;

			// Format phone number
			var text = formatter.input(value);

			return { text: text, template: formatter.template };
		}
	}, {
		key: 'on_key_down',
		value: function on_key_down(event) {
			// on "Down arrow"
			if (event.keyCode === 40) {
				this.select.toggle();
			}
		}
	}, {
		key: 'on_change',
		value: function on_change(value) {
			var country_code = arguments.length <= 1 || arguments[1] === undefined ? this.state.country_code : arguments[1];
			var onChange = this.props.onChange;


			if (!value) {
				this.setState({ value: value });
				return onChange(value);
			}

			// If a phone number is being input as an international one
			// and the country code can already be derived,
			// then switch the country.
			if (value && value[0] === '+' && this.formatter.country && this.formatter.country !== '001') {
				this.setState({ country_code: this.formatter.country });
			}

			// If the phone number is being input in a country-specific format
			//   If the value has a leading + sign
			//     The value stays as it is
			//   Else
			//     The value is converted to international plaintext
			// Else, the phone number is being input in an international format
			//   If the value has a leading + sign
			//     The value stays as it is
			//   Else
			//     The value is prepended with a + sign

			if (country_code) {
				if (value[0] === '+') {
					onChange(value);
				} else {
					onChange((0, _libphonenumberJs.format)(parse_national_number(value, country_code), country_code, 'International_plaintext'));
				}
			} else {
				if (value[0] === '+') {
					onChange(value);
				} else {
					value = '+' + value;
					onChange(value);
				}
			}

			this.setState({ value: value });
		}
	}, {
		key: 'render',
		value: function render() {
			var _this2 = this;

			var _props = this.props;
			var dictionary = _props.dictionary;
			var saveOnIcons = _props.saveOnIcons;
			var countries = _props.countries;
			var internationalIcon = _props.internationalIcon;
			var country = _props.country;
			var flagsPath = _props.flagsPath;
			var disabled = _props.disabled;
			var style = _props.style;
			var className = _props.className;
			var input_props = (0, _objectWithoutProperties3.default)(_props, ['dictionary', 'saveOnIcons', 'countries', 'internationalIcon', 'country', 'flagsPath', 'disabled', 'style', 'className']);


			var items = [{
				value: '-',
				label: dictionary.International || 'International',
				icon: internationalIcon
			}].concat(countries || country_options);

			var markup = _react2.default.createElement(
				'div',
				{ style: style, className: (0, _classnames2.default)('react-phone-number-input', className) },
				_react2.default.createElement(_reactResponsiveUi.Select, {
					ref: function ref(_ref3) {
						return _this2.select = _ref3;
					},
					value: this.state.country_code || '-',
					options: items,
					onChange: this.set_country,
					disabled: disabled,
					autocomplete: true,
					concise: true,
					focusUponSelection: false,
					saveOnIcons: saveOnIcons === undefined ? !countries : saveOnIcons,
					name: input_props.name ? input_props.name + '__country' : undefined }),
				_react2.default.createElement(_inputFormat.ReactInput, (0, _extends3.default)({}, input_props, {
					ref: function ref(_ref4) {
						return _this2.input = _ref4;
					},
					value: this.state.value,
					onChange: this.on_change,
					disabled: disabled,
					type: 'tel',
					parse: this.parse,
					format: this.format,
					onKeyDown: this.on_key_down }))
			);

			return markup;
		}
	}]);
	return Input;
}(_react.Component);

Input.propTypes = {
	// Phone number `value`.
	// Is a plaintext international phone number
	// (e.g. "+12223333333" for USA)
	value: _react.PropTypes.string,

	// This handler is called each time
	// the phone number <input/> changes its textual value.
	onChange: _react.PropTypes.func.isRequired,

	// This `onBlur` interceptor is a workaround for `redux-form`,
	// so that it gets a parsed `value` in its `onBlur` handler,
	// not the formatted one.
	// (`redux-form` passed `onBlur` to this component
	//  and this component intercepts that `onBlur`
	//  to make sure it works correctly with `redux-form`)
	onBlur: _react.PropTypes.func,

	// Disables both the <input/> and the <select/>
	disabled: _react.PropTypes.bool.isRequired,

	// Two-letter country code
	// to be used as the default country
	// for local (non-international) phone numbers.
	country: _react.PropTypes.string,

	// Localization dictionary:
	// `{ International: 'Международный', RU: 'Россия', US: 'США', ... }`
	dictionary: _react.PropTypes.objectOf(_react.PropTypes.string),

	// A custom selectable options list.
	// May be used to show all country flags in the <select/> list.
	//
	// Example:
	//
	// SVG flags for all countries (3 MegaBytes in size).
	// Too big for the public internet, but may be suitable
	// for enterprise software (e.g. CRM systems).
	// import countriesWithFlags from 'react-phone-number-input/countries-with-flags'
	//
	// <Phone ... countries={countriesWithFlags}/>
	//
	// (and that should be working)
	//
	countries: _react.PropTypes.arrayOf(_react.PropTypes.shape({
		// Option value
		value: _react2.default.PropTypes.string.isRequired,
		// Option label
		label: _react2.default.PropTypes.string.isRequired,
		// Option icon
		icon: _react2.default.PropTypes.element
	})).isRequired,

	// If set to `false`, then country flags will be shown
	// for all countries in the options list
	// (not just for selected country).
	saveOnIcons: _react.PropTypes.bool,

	// Custom "International" phone number type icon.
	internationalIcon: _react.PropTypes.element.isRequired,

	// A base URL path for national flag SVG icons.
	// By default it uses the ones from `flag-icon-css` github repo.
	flagsPath: _react.PropTypes.string.isRequired,

	// CSS style object
	style: _react.PropTypes.object,

	// CSS class
	className: _react.PropTypes.string
};
Input.defaultProps = {
	// Is enabled
	disabled: false,

	// By default use the ones from `flag-icon-css` github repo.
	flagsPath: 'https://lipis.github.io/flag-icon-css/flags/4x3/',

	// Default international icon (globe)
	internationalIcon: _react2.default.createElement(
		'div',
		{ className: 'react-phone-number-input__icon react-phone-number-input__icon--international' },
		_react2.default.createElement(_internationalIcon2.default, null)
	),

	// Default country labels
	countries: country_options,

	// Custom country names
	dictionary: {},

	// Don't show flags for all countries in the options list
	// (show it just for selected country).
	// (to save user's traffic because all flags are about 3 MegaBytes)
	saveOnIcons: true
};
exports.default = Input;


function parse_national_number(value, country_code) {
	// "As you type" formatter
	var formatter = new _libphonenumberJs.as_you_type(country_code);

	// Format phone number
	formatter.input(value);

	return formatter.national_number;
}
module.exports = exports['default'];
//# sourceMappingURL=input.js.map