package dev.peerat.backend.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import dev.peerat.framework.HttpReader;
import dev.peerat.framework.Response;
import dev.peerat.framework.utils.json.Json;
import dev.peerat.framework.utils.json.JsonMap;

public abstract class FormResponse implements Response{

	private Json json;
	private Map<String, Pattern> checker;
	
	public FormResponse(){
		this.checker = new HashMap<>();
	}
	
	public void validator(String key, String regex){
		this.checker.put(key, Pattern.compile(regex, Pattern.CASE_INSENSITIVE));
	}
	
	public <T extends Json> T json(HttpReader reader) throws Exception{
		return (T) (this.json = reader.readJson());
	}
	
	public boolean hasFields(String... fields){
		JsonMap map = (JsonMap)json;
		for(String field : fields){
			if(!map.has(field)) return false;
		}
		return true;
	}
	
	public boolean areValids(String... fields){
		JsonMap map = (JsonMap)json;
		for(String field : fields){
			String value = (String) map.get(field);
			if(value == null) return false;
			if(value.isEmpty()) return false;
			Pattern pattern = checker.get(field);
			if(pattern == null) continue;
			if(!pattern.matcher(value).matches()) return false;
		}
		return true;
	}
}
