package dev.peerat.backend.utils;

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

import org.json.simple.JSONAware;

import dev.peerat.framework.HttpReader;
import dev.peerat.framework.Response;

public abstract class FormResponse implements Response{

	private JSONAware json;
	private Map<String, Pattern> checker;
	
	public FormResponse(){
		this.checker = new HashMap<>();
	}
	
	public void validator(String key, Pattern regex){
		this.checker.put(key, regex);
	}
	
	public <T extends JSONAware> T json(HttpReader reader) throws Exception{
		return (T) (this.json = reader.readJson());
	}
	
	public boolean hasFields(String... fields){
		Map<?,?> map = (Map<?,?>)json;
		for(String field : fields){
			if(!map.containsKey(field)) return false;
		}
		return true;
	}
	
	public boolean areValids(String... fields){
		Map<?,?> map = (Map<?,?>)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;
	}
}
