/**
 * 
 */
package com.ibm.vista.sqltrigger;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static java.nio.charset.StandardCharsets.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

/**
 * @author Gerry Broennimann
 *
 */
public class Query {

	public String[] environments = null;
	public String queryname	= "";
	//public String sql = "";
	
	public Query() {
		String jsonString = "";
		
		try {
			// step 1: Load the query.json file
			InputStream queryStream = new FileInputStream("./queries/query.json");
			InputStreamReader queryReader = new InputStreamReader(queryStream);
			BufferedReader br = new BufferedReader(queryReader);
			String line = "";
			while ((line = br.readLine()) != null) {
				jsonString += line + "\n";
			}
			// Handle UTF-8 issues (Umlauts like ä, ö, ü, Ä, ... )
			byte[] ptext = jsonString.getBytes(ISO_8859_1); 
			String utf8 = new String(ptext, UTF_8);
			
			JSONObject jsonObject = new JSONObject(utf8);
			
			// step 2: Read the configuration details
			this.queryname = (String) jsonObject.getString("queryname");
			//this.sql = (String) jsonObject.getString("sql");
			JSONArray environmentsArray = jsonObject.getJSONArray("environments");
			this.environments = new String[environmentsArray.length()];
			for (int i=0; i<environmentsArray.length(); i++) {
				this.environments[i] = environmentsArray.getString(i);
			}
			br.close();	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
