import Input from './Input.jsx';

function setCaretPosition(el, caretPos) {
  el.value = el.value;
  // ^ this is used to not only get "focus", but
  // to make sure we don't have it everything -selected-
  // (it causes an issue in chrome, and having it doesn't hurt any other browser)

  if (el !== null) {

    if (el.createTextRange) {
      var range = el.createTextRange();
      range.move('character', caretPos);
      range.select();
      return true;
    }

    else {
      // (el.selectionStart === 0 added for Firefox bug)
      if (el.selectionStart || el.selectionStart === 0) {
        el.focus();
        el.setSelectionRange(caretPos, caretPos);
        return true;
      }

      else  { // fail city, fortunately this never happens (as far as I've tested) :)
        el.focus();
        return false;
      }
    }
  }
};

export default D.declare('view.cmp.field.PhoneInput', (cfg, children)=> {
  let displayDOM,placeholderDOM, inputDOM,
      dom = <div class='field__input-wrapper field__phone-wrapper'>
        {displayDOM = <div class={'field__phone-display'}/>}
        {placeholderDOM = <div class={'field__phone-placeholder'}>{cfg.placeholder||'Ваш номер'}</div>}


        <div class='field__input'>
          {inputDOM =
            <input
              class="field__input field__phone-hidden"
              type={'tel'}
            />
          }

        </div>

      </div>;
  let focused = false;

  if(cfg.bind){
    var update = function (val) {
      val = val+'';
      inputDOM.value = val;
      let built = [];
      if((val !== '' && val !== '7' && val !== '8') || focused){
        const pattern = '+0 (000) 000-00-00';
        let pos = 0;
        for( let i = 0, _i = pattern.length; i < _i; i++ ){
          const char = pattern[ i ];
          if( char === '0' ){
            built.push( val[ pos ] === void 0 ? ' ' : val[ pos ] );
            pos++;
          }else{
            built.push( char );
          }
        }
      }
      if(built.length === 0){
        placeholderDOM.classList.add('field__phone-placeholder__visible');
      }else{
        placeholderDOM.classList.remove('field__phone-placeholder__visible');
      }
      displayDOM.innerText = built.join('');

    };
    cfg.bind.sub(update);
    inputDOM.addEventListener('keypress', function (e) {
      if(inputDOM.value.length+(e.data!==null?e.key.length:0)>12){
        e.preventDefault()
      }
      valueGetter();
    });
    var valueGetter = function() {
      cfg.bind.set((inputDOM.value+'').substr(0,11));
    };
    inputDOM.addEventListener('keyup', valueGetter);
    inputDOM.addEventListener('input', valueGetter);

    var focus = function(e) {
      focused = true;
      setTimeout(()=> setCaretPosition(inputDOM, inputDOM.value.length),0);
      update(inputDOM.value);
    };
    inputDOM.addEventListener('focus', focus);
    inputDOM.addEventListener('click', focus);

    inputDOM.addEventListener('blur', function() {
      focused = false;
      update(inputDOM.value);
    });
  }

  return dom;
})
