# TODO: Add comment
# 
# Author: E.Korsching  2024
###############################################################################


#### libre office  'select/(auto-)filter'  functionality


lo.select <- function(x, z, op, ...){
	# filter over all given columns and return the remaining target column set
	# x: one to n columns to filter
	# z: target column - needs to correspond to x obviously
	# op: one to n operators ("!=","==",">","<", etc.)
	# ... : exact one argument per column in x, could be also be a vector per column
	#  type of argument needs to correspond to column type
	nr <- nrow(x)
	nc <- ncol(x)
	opl <- length(op)
	if(opl!=nc){ stop(paste("number of op does not correspond to x:",opl,sep="")) }
	colargs <- list(...)
	arg.n <- length(colargs)
	if(arg.n!=nc){ stop(paste("number of arguments does not correspond to x:",arg.n,sep="")) }
	arg.c <- nargs() -3
	if(arg.c!=nc){ stop(paste("number of arguments does not fit:",arg.c,sep="")) }
	mat <- matrix(0,nr,nc)
	for(i in 1:nc){
		cai <- length(colargs[[i]])
		if(cai==1){
			mat[,i] <- get(op[i])(x[,i], colargs[[i]])
		}else if(cai>1){
			tmp <- matrix(0,nr,cai)
			k <- 1
			for(j in 1:cai){
				tmp[,j] <- get(op[i])(x[,i], colargs[[i]][j])
			}
			mat[,i] <- apply(tmp,1, function(x){if(sum(x)>0){1}else{0}} )	# always 'or'
		}
	}
	print(mat)
	res <- apply(mat,1, function(x){if(sum(x, na.rm=T)==nc){T}else{F}} )	# always 'and'
	out <- z[res]
	return(out)
}

#lo.select(x=data.frame(a1=c(1,3,2,1,3), a2=c("aa","c","c","d","aa")), z=c("x1","x2","x3","x4","x5"), op=c("!=","=="), 1, c("c","d"))



