import {Component} from 'cmp/Component.jsx';


var TimeInput = new Component({
  name: 'TimeInput',
  ctor: function(cfg) {
    Object.assign(this, cfg);

    this.createDOM();
    this.initBinding();

    this.afterInit && this.afterInit();
  },
  prop: {
    value: {type: Number, default: false},
    min: {type: Number, default: 0},
    max: {type: Number, default: 24*60*60},
  },
  createDOM: function() {
    var _self = this;

    this.dom = D.div({cls: 'TimeInput'},
      this.minuteEl = D.h('input', {
        attr: {type: 'number'},
        cls: 'cmp-input minute',
        oninput: function() {
          _self.store.set('minutes', _self.minuteEl.value|0);
        }
      }), ':',
      this.secondEl = D.h('input', {
        attr: {type: 'number'},
        cls: 'cmp-input second',
        oninput: function() {
          var val = _self.secondEl.value |0;
          if(val<0){
            _self.store.set({
              'minutes': _self.store.get('minutes')-1,
              'seconds': 59
            });
          }else if(val>59){
            _self.store.set({
              'minutes': _self.store.get('minutes')+1,
              'seconds': 0
            });
          }else{
            _self.store.set('seconds', val);
          }
        }
      })
    );

    this.afterDOM && this.afterDOM();
  },
  initBinding: function() {
    var _self = this;

    this.sub([this.value], function (val) {
      var sec = (val % 60) |0,
          min = (val / 60) |0;

      _self.store.set({
        minutes: min,
        seconds: sec
      });

    });
    this.sub(['minutes', 'seconds'], function(min, sec) {
      _self.value.set(min*60 + sec);
      _self.minuteEl.value = min;
      _self.secondEl.value = sec;
    });

  }
});

export { TimeInput };
