'use strict';

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

var _constants = require('../constants');

var _isCharLongDash = require('./isCharLongDash');

var _isCharLongDash2 = _interopRequireDefault(_isCharLongDash);

var _isCharSlashDot = require('./isCharSlashDot');

var _isCharSlashDot2 = _interopRequireDefault(_isCharSlashDot);

var _isCharKatakana = require('./isCharKatakana');

var _isCharKatakana2 = _interopRequireDefault(_isCharKatakana);

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

/**
 * Convert [Katakana](https://en.wikipedia.org/wiki/Katakana) to [Hiragana](https://en.wikipedia.org/wiki/Hiragana)
 * Passes through any non-katakana chars
 * @param  {String} [input=''] text input
 * @return {String} converted text
 * @example
 * katakanaToHiragana('カタカナ')
 * // => "かたかな"
 * katakanaToHiragana('カタカナ is a type of kana')
 * // => "かたかな is a type of kana"
 * @ignore
 */
function katakanaToHiragana() {
  var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

  var hira = [];
  var previousKana = '';
  var iterable = input.split('');
  for (var index = 0; index < iterable.length; index += 1) {
    var char = iterable[index];
    var _ref = [(0, _isCharSlashDot2.default)(char), (0, _isCharLongDash2.default)(char)],
        slashDot = _ref[0],
        longDash = _ref[1];
    // Short circuit to avoid incorrect codeshift for 'ー' and '・'

    if (slashDot || longDash && index < 1) {
      hira.push(char);
      // Transform long vowels: 'オー' to 'おう'
    } else if (previousKana && longDash && index > 0) {
      // Transform previousKana back to romaji, and slice off the vowel
      var romaji = _constants.TO_ROMAJI[previousKana].slice(-1);
      hira.push(_constants.LONG_VOWELS[romaji]);
    } else if (!longDash && (0, _isCharKatakana2.default)(char)) {
      // Shift charcode.
      var code = char.charCodeAt(0) + (_constants.HIRAGANA_START - _constants.KATAKANA_START);
      var hiraChar = String.fromCharCode(code);
      hira.push(hiraChar);
      previousKana = hiraChar;
    } else {
      // Pass non katakana chars through
      hira.push(char);
      previousKana = '';
    }
  }
  return hira.join('');
}

exports.default = katakanaToHiragana;