/*
 * @author Ranides Atterwim {@literal <ranides@gmail.com>}
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */

package net.ranides.assira.reflection.impl.bean;

import java.io.Serializable;
import java.util.List;
import net.ranides.assira.collection.arrays.NativeArray;
import net.ranides.assira.collection.arrays.NativeArrayAccess;
import net.ranides.assira.collection.arrays.NativeArrayUtils;
import net.ranides.assira.collection.lists.VirtualList;
import net.ranides.assira.functional.special.AnyFunction;
import net.ranides.assira.generic.ValueUtils;
import net.ranides.assira.reflection.*;
import net.ranides.assira.reflection.util.ClassUtils;

/**
 * Represents indexed bean property as List. "value" getter &amp; setter should return array.
 * Optional "index" getter &amp; setter should return/take type identical to array component.
 * 
 * #set unwraps passed list to array and use "value setter"
 * 
 * #get returns VirtualList:
 *      list contains "cached" data obtained by "value getter"
 *      #get(index) uses "index getter" if declared, or cached value otherwise 
 *      #set(index) changes content of virtual list 
 *      #set(index) use "index setter" if declared to modify bean's content instantly 
 *      #size() returns size of cached data 
 * 
 * Please note that if "index setter" isn't declared, you have to manually return back modified list:
 * {@code
 *      List<Object> list = property.get(bean)
 *      list.set ...
 *      property.set(list)
 * }
 * Please note that structural changes have to be manually returned back even if you declared "index setter":
 * {@code
 *      List<Object> list = property.get(bean)
 *      list.remove ...
 *      list.add ...
 *      property.set(list)
 * }
 */
public class RPArray extends ABeanProperty implements Serializable {

    private static final long serialVersionUID = 2L;
    
    private final Class<?> component;
    private final NativeArrayAccess access;
    
    private final IMethod vgetter;
    private final IMethod vsetter;
    private final IMethod igetter;
    private final IMethod isetter;

    RPArray(RBeanPropertyBuilder info) {
        super(itype(info), info.name());
        this.component = info.item().raw();
        this.access = NativeArrayAccess.forComponent(component);
        
        this.vgetter = info.vgetter();
        this.vsetter = info.vsetter();
        this.igetter = info.igetter();
        this.isetter = info.isetter();
    }
    
    private static IClass<?> itype(RBeanPropertyBuilder info) {
        return IClass.generic(List.class, ClassUtils.box(info.item()));
    }
        
    @Override
    public void set(Object that, Object value) {
        checkWA();
        if(null == value) {
            vsetter.invoke(that, new Object[]{null});
        } else {
            List<?> source = (List<?>)value;
            NativeArray target = NativeArray.allocate(component, source.size());
            NativeArrayUtils.collect(source.iterator(), target);
            vsetter.invoke(that, new Object[]{target.$array()});
        }
    }

    @Override
    public Object get(Object that) {
        checkRA();
        Object array = vgetter.invoke(that);
        return array!=null ? new ArrayWrapper(this, that, array) : null;
    }

    @Override
    public boolean isReadable() {
        return vgetter != null;
    }

    @Override
    public boolean isWritable() {
        return vsetter != null;
    }

    @Override
    public IClass<?> parent() {
        return ValueUtils.or(vgetter, vsetter, igetter, isetter).parent();
    }

    private void checkRA() {
        if(!isReadable()) {
            throw FBeanModel.newUnsupportedOperationException("property " + name() + " is read-only");
        }
    }
    
    private void checkWA() {
        if(!isWritable()) {
            throw FBeanModel.newUnsupportedOperationException("property " + name() + " is write-only");
        }
    }
    
    private static final class ArrayWrapper extends VirtualList<Object> {
        
        private static final long serialVersionUID = 1L;

        private final NativeArray data;
        private final AnyFunction<?> mset;
        private final AnyFunction<?> mget;

        public ArrayWrapper(RPArray rpa, Object that, Object array) {
            this.data = rpa.access.bind(array);
            this.mget = null != rpa.igetter ? rpa.igetter.bind(that) : null;
            this.mset = null != rpa.isetter ? rpa.isetter.bind(that) : null;
        }

        @Override
        public int size() {
            return data.size();
        }

        @Override
        public Object get(int index) {
            if(null != mget) {
                return mget.call(index);
            } else {
                return data.get(index);
            }
        }

        @Override
        public Object set(int index, Object element) {
            Object prv = data.replace(index, element);
            if(null != mset) {
                prv = mset.call(index, element);
            }
            return prv;
        }

    }
    
}
