package syndiff;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Config {
	private Map<String, String> tidb;
	private Map<String, String> sourcedb;
	private Map<String, String> checkconfig;
	private List<Map<String,String>> schema_mapping_rule;
	private static int CHECK_TABLE = 1;
	private static int CHECK_VIEW = 2;
	private static int CHECK_INDEX = 3;
	private static int MAX_THREADS = 100;
	
	public Map<String, String> getSchemaMapping() {
		Map<String, String> m = new HashMap<String, String>();
		if (schema_mapping_rule == null ) return m;
		
		schema_mapping_rule.forEach(x -> {
			String s = x.get("source-schema");
			String t = x.get("tidb-schema");
			if (s == null || s.length() == 0 || t== null || t.length() == 0) {
				System.out.println("invalid schema mapping rule, skip it!");
			} else {
				m.put(t.toLowerCase(), s.toLowerCase());
			}
		});
		return m;
	}
	public boolean checkTable() {
		return checkScope(CHECK_TABLE);
	}
	public boolean checkView() {
		return checkScope(CHECK_VIEW);
	}
	public boolean checkIndex() {
		return checkScope(CHECK_INDEX);
	}
	private boolean checkScope(int difftype) {
		if (checkconfig != null) {
			String ckscope = checkconfig.get("check-scope");
			if (ckscope == null || ckscope.trim().length() == 0) return true;
			if (difftype == CHECK_TABLE) return ckscope.toLowerCase().indexOf("table") > -1;
			if (difftype == CHECK_VIEW)  return ckscope.toLowerCase().indexOf("view") > -1;
			if (difftype == CHECK_INDEX) return ckscope.toLowerCase().indexOf("index") > -1;
			return false;
		}
		return true;
	}
	public int getCheckRowTimeout() {
		if (checkconfig != null) {
			String ckrow = checkconfig.get("check-row-count-timeout");
			try{
				int timeout = Integer.parseInt(ckrow);
				return timeout > 0 ? timeout : 0;
			}catch(Exception e) {
				return 0;
			}
		}
		return 0;
	}
	public boolean checkRows() {
		if (checkconfig != null) {
			String ckrow = checkconfig.get("check-row-count");
			return ckrow != null && ckrow.trim().toLowerCase().equals("true");
		}
		return false;
	}
	public int getSourceCheckThreads() {
		return getCheckThreads("check-row-source-threads");
	}
	public int getTargetCheckThreads() {
		return getCheckThreads("check-row-target-threads");
	}
	private int getCheckThreads(String key) {
		String threads = checkconfig.get(key);
		if (threads == null) return 2; //default 2 threads max:15
		try{
			int c = Integer.parseInt(threads);
			return c <= 0 ? 2 : c > MAX_THREADS ? MAX_THREADS : c;
		}catch(Exception e) {
			return 2;
		}
	}
}

