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

var PlainSelect  = new Component( {
  ctor: function(){
    var vals = this.values.get()
      .split('\n')
      .map(a=>a.trim())
      .filter(String),

      _self = this;

    this.values.set(vals.map(function(val) {
      var item = {},
          selected = false;

      if(val[0] === '>'){
        val = val.substr(1);
        selected = true;
      }

      var tokens = val.split(':');
      if(tokens.length === 1){
        tokens.push( tokens[ 0 ] );
      }

      item.id = tokens[0].trim();
      item.text = tokens.slice(1).join(':').trim();

      if(selected){
        _self.value.set( item.id );
      }

      return item;
    }));

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

    this.afterInit && this.afterInit();
  },
  prop: {
    value: { type: Component.Property.Any, default: false },
    values: { type: Component.Property.Any, default: '' },
    map: { type: Function, default: false }
  },
  createDOM: function() {
    this.dom = <select>
      {
        this.values.get().map(item=>
          D.h('OPTION', {value: item.id}, item.text)
        )
      }
    </select>;
  },
  initBinding: function() {
    var _self = this;
    this.value.sub(function (val) {
      _self.dom.value = val;
    });

    _self.dom.addEventListener('change', function () {
      _self.value.set(_self.dom.value);
    });

  }
});

export {PlainSelect};