AddCss('/view/select.css');

var Select = function(cfg) {
	let isOpen = this.isOpen = new Store.Value.Boolean(false);
	let isDisabled = this.isDisabled = cfg.disabled || new Store.Value.Boolean(false);

	var table = D.div({cls: 'dropdown-list'}, _=>{
		store.sub([cfg.values, cfg.filter], function(val, filter) {
			if(val){
				var possibleValues = [];
				_(val.map(function(v) {
					if(cfg.filter && v.filter !== filter)
						return;
					possibleValues.push(v);
					return D.div({cls: 'dropdown-item', 'data-id': v.value, onclick: function() {
							cfg.bind.set(v.value);
							isOpen.set(false);
							unSubscribeFadeClick();
						}}, v.text)
				}));

				if(possibleValues.length){
					var currentValue = cfg.bind.get();
					if( !( possibleValues.find( val => val.value === currentValue ) ) ){
						cfg.bind.set( possibleValues[ 0 ].value );
					}
				}

			}
		});
	});

	var subscribed = false;
	var documentClick = function(e) {
		if(D.findParent(e.target, p=>p === dom) === void 0){
			isOpen.set(false);
			unSubscribeFadeClick();
		}
	};
	var subscribeFadeClick = function() {
		if(!subscribed){
			subscribed = true;
			document.addEventListener( 'click', documentClick );
		}
	}
	var unSubscribeFadeClick = function() {
		if(subscribed){
			document.removeEventListener( 'click', documentClick );
			subscribed = false;
		}
	}
	var dom = D.div({cls: 'form-field'},
		D.div({cls: 'form-field__label'},
			D.span({cls: 'form-field__label-text'}, cfg.label),
			D.div({cls: ['dropdown-field', {
						'dropdown-field--opened': isOpen,
						'dropdown-field--disabled': isDisabled
					}]},
				D.h('button', {
						cls: 'dropdown-field__toggler',
						onclick: () => {
							isOpen.toggle();
							if(isOpen.get() === true){
								subscribeFadeClick();
							}
						}
					},
					D.span({cls: D.cls(
							"dropdown-field__placeholder", {
								"dropdown-field__placeholder--filled": _=>cfg.bind.sub(val=>_(!!(cfg.multivalue ? val && val.length : val && val.name)))
							} )},
						_ => {
							cfg.bind.sub( val => {
								if( val ){
									var vals = store.get(cfg.values) || [],
										theVal = vals.filter(v=>v.value === val)[0];

									_(theVal?theVal.text: 'Select')
								}else{
									_( cfg.placeholder );
								}
							} );
						}
					)
				),
				D.div({cls: 'dropdown-field__tooltip'},
					table
				)

			)
		)
	);
	return dom;
}