import com.rameses.rcp.annotations.*;
import com.rameses.osiris2.common.*;
import com.rameses.osiris2.client.*;
import com.rameses.rcp.common.*;
import java.util.*;

public class ListTypes extends HashMap {
    
    @Service("QueryService")
    def qryService;

    @Service("ListService")
    def listService;
    
    def schema;
    def _handlers = [:];

    void init( def s ) {
        schema = s;
        _handlers = [:];
    }

    void setHandlers( handlers ) {
        this._handlers = handlers; 
    }
    
    /***
    * the ff. attributes of the field supported
    *    lov = field has lov. list calling LOV
    *    ref = field has ref. list calling queryService.getList
    *    listname = display list immediately
    *    openerlist = display list of openers
    *    default: lookup list based on name passed
    ***/
    public def get( def n ) {
        def fld = null;
        if(schema!=null) {
            fld = (schema.fields+schema.links).find{ it.extname == n }; 
        }
        if(fld!=null) {
            if( fld?.lov!=null ) {
                return LOV.get( fld.lov.toUpperCase() )*.key;
            } else if(fld?.ref!=null) {
                try {
                    String nn = fld.ref;
                    if(nn.indexOf(".")>0) nn = nn.split(":")[1];
                    def m = [_schemaname:nn];
                    if(fld.includefields) {
                        m.select = fld.includefields;
                    }    
                    if ( _handlers.containsKey(n) ) {
                        m.findBy = _handlers.get(n)();
                    }
                    m._limit =1000;
                    m._start = 0;
                    return  qryService.getList( m );
                } catch(e) {
                    e.printStackTrace();
                }
            } else if(fld?.listname!=null) {
                try {
                    return listService.getList([name: fld.listname]);
                } catch(e) {
                    e.printStackTrace();
                }
            } else if(fld?.openerlist!=null) {
                try {
                    return Inv.lookupOpeners( fld.openerlist );
                } catch(e) {
                    e.printStackTrace();
                }
            }
        } else {
            //test the simple lists
            try {
                return listService.getList([name: n]);
            } catch(e) {
                e.printStackTrace();
            }
        }
        return [];
    }   
}