const RadioGroup = (($) => {
    const DefaultConfig = {
        group:[],
        onChange:null,      
        selectedValue:null,
        beforeDispose:null,
    };
    class RadioGroup {
        constructor(config) {
            this.__name = "RadioGroup";
            this._config = this._getConfig(config);
            this.group = this._config.group;
            this.selectedRadio = null;
            this._addEvent();
            if(this._config.selectedValue!=undefined){
                this.setSelectedValue(this._config.selectedValue);
            }
            else{
                if(this.group){
                    this.group.map((radio, i)=>{
                        radio.render();
                        if(radio.getChecked()){
                            this.selectedRadio = radio;
                        }
                    });
                }
            }
        }
        
        _getConfig(config) {
            return $.extend(true, {}, DefaultConfig, config);
        }
        _addEvent(){
            if(this.group){
                this.group.map((radio, i)=>{
                    radio.setChangeCallback(this.onRadioChange.bind(this));
                });
            }
        }
        
        setSelectedValue(curValue){
            if(curValue != undefined && (this.selectedRadio == null || this.selectedRadio.getValue()!=curValue)){
                let curRadio = null;
                if(this.group){
                    this.group.map((radio, i)=>{
                        if(radio.getValue() == curValue){
                            curRadio = radio;
                            this.selectedRadio = radio;
                            curRadio.setChecked(true);
                        }
                        else{
                            radio.setChecked(false);
                        }
                        radio.render();
                    });
                }
                const {onChange} = this._config;
                if(onChange!=null && curRadio){
                    onChange(curValue, curRadio.label, curRadio.groupName);
                }
            }
        }
        getSelectedValue(){
            if(this.selectedRadio){
                return this.selectedRadio.getValue();
            }
            return null;
        }
        onRadioChange(value, label, groupName){
            this.setSelectedValue(value);
        }
        
        dispose() {
            const {beforeDispose} = this._config;
            if(beforeDispose){
                beforeDispose();
            }
            if(this.group){
                for(let i=0;i<this.group.length;i++){
                    let radio = this.group[i];
                    radio.dispose();
                }
            }
            this.selectedRadio = null;
            this.group = null;
        }
    }
    return RadioGroup;
})($);
export default RadioGroup;