package com.madeu.api;

import static org.hamcrest.CoreMatchers.equalTo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Component
public class InBodyApiProvider{
	
	// INBODY API LBWEB ID
	@Value("${inbody.api.lbwebid}")
	String inbody_lbwebid;
	
	// INBODY API KEY
	@Value("${inbody.api.secret}")
	String inbody_secret;
	
	// DATETIME URL
	@Value("${inbody.api.datetimeurl}")
	String inbody_datetimeurl;
	
	// FULL INBODY URL
	@Value("${inbody.api.fullinbodyurl}")
	String inbody_fullinbodyurl;
	
	/**
	 * 
	 * 회원의 {usertoken}과 일치하는 InBody 테스트 날짜/시간 조회 (Inbody 날짜 정보 조회)
	 * 
	 * */
	public String getDateTimes(String usertoken){
		log.debug("InBodyApiProvider getDateTimes START");
		
		String result = "";
		try {
			// 파라미터 셋팅
			JSONObject jsonData = new JSONObject();
			jsonData.put("usertoken", usertoken);
			
			
			URL obj = new URL(inbody_datetimeurl);
			
			BufferedReader rd = null;
			InputStreamReader isr = null;
			try {
				HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
				con.setRequestMethod("POST");
				con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
				con.setRequestProperty("Accept", "application/json");
				con.setRequestProperty("Account", inbody_lbwebid);
				con.setRequestProperty("API-KEY", inbody_secret);
				con.setDoOutput(true); // InputStream으로 서버로 부터 응답을 받겠다는 옵션.
				
				// 파라미터 전송
				PrintWriter pw = new PrintWriter(new OutputStreamWriter(con.getOutputStream()));
				pw.write(jsonData.toString());
				pw.flush();
				
				isr = new InputStreamReader(con.getInputStream(), "UTF-8");
				rd = new BufferedReader(isr);
	
				final StringBuffer buffer = new StringBuffer();
				String line;
				while ((line = rd.readLine()) != null) {
					buffer.append(line);
				}

				log.debug("result : "+buffer.toString());
				result = buffer.toString();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// clear resources
				if (rd != null) {
					try {
						rd.close();
					} catch(Exception ignore) {
					}
				}
				if (isr != null) {
					try {
						isr.close();
					} catch(Exception ignore) {
					}
				}
				
				
			}
		} catch (Exception e){
			log.debug("error : "+e.toString());
		}

		log.debug("InBodyApiProvider getDateTimes END");
		
		return result;
	}
	
	/**
	 * 
	 * 회원의 InBody 측정 데이터에서 {datetimes}까지 일치하는 {usertoken}을 검색 (Inbody 정보 조회)
	 * 
	 * */
	public String getFullInBodyData(String usertoken, String dataTimes){
		log.debug("InBodyApiProvider getFullInBodyData START");
		
		String result = "";
		try {
			// 파라미터 셋팅
			JSONObject jsonData = new JSONObject();
			jsonData.put("usertoken", usertoken);
			jsonData.put("datetimes", dataTimes);
			
			
			URL obj = new URL(inbody_fullinbodyurl);
			
			BufferedReader rd = null;
			InputStreamReader isr = null;
			try {
				HttpsURLConnection con = (HttpsURLConnection)obj.openConnection();
				con.setRequestMethod("POST");
				con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
				con.setRequestProperty("Accept", "application/json");
				con.setRequestProperty("Account", inbody_lbwebid);
				con.setRequestProperty("API-KEY", inbody_secret);
				con.setDoOutput(true); // InputStream으로 서버로 부터 응답을 받겠다는 옵션.
				
				// 파라미터 전송
				PrintWriter pw = new PrintWriter(new OutputStreamWriter(con.getOutputStream()));
				pw.write(jsonData.toString());
				pw.flush();
				
				isr = new InputStreamReader(con.getInputStream(), "UTF-8");
				rd = new BufferedReader(isr);
	
				final StringBuffer buffer = new StringBuffer();
				String line;
				while ((line = rd.readLine()) != null) {
					buffer.append(line);
				}

				log.debug("result : "+buffer.toString());
				result = buffer.toString();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				// clear resources
				if (rd != null) {
					try {
						rd.close();
					} catch(Exception ignore) {
					}
				}
				if (isr != null) {
					try {
						isr.close();
					} catch(Exception ignore) {
					}
				}
			}
		} catch (Exception e){
			log.debug("error : "+e.toString());
		}

		log.debug("InBodyApiProvider getFullInBodyData END");
		
		return result;
	}
}