package org.keyscience;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class PHPResponseTest {
    public static String userJsonDir = "src/phpresponsetest/user_details.json";

    public static File userJsonPath = new File(userJsonDir);
    public static boolean userLoggedIn = userJsonPath.exists();

    @Test
    public void retrieveUserDetails() throws IOException {
//        userLogout();
//
//        if ( userLoggedIn )
//        {
//            System.out.println("User already logged in.");
//            return;
//        }

        HashMap<String, String> userCredentials = new HashMap<>();
        String user_login = "9999";
        String user_pass = "6";

        userCredentials.put("user_id", user_login);
   //     userCredentials.put("ecoquest_id", user_pass);

        String urlParameters = getDataString(userCredentials);

        // POST CALL
        byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
        int postDataLength = postData.length;

        String request = "http://keyscience.org/wp-content/app/EcoQuest/userEcoQuests.php";

        URL url = new URL( request );
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setInstanceFollowRedirects(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
        conn.setUseCaches(false);

        try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.write( postData );

            // READ PHP OUTPUT
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                System.out.println(inputLine);
                if (!inputLine.equals("FAIL!")) {
                // Write JSON to Cache
//                    OutputStream outputStream = new FileOutputStream(userJsonDir);
//
//                    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
//                    outputStreamWriter.write(inputLine);
//                    outputStreamWriter.close();

//                    readUserJson(inputLine);
                }
            }
            in.close();
        }
    }
//
//    private static void userLogout() {
//        if ( userJsonPath.exists() )
//            userJsonPath.delete();
//    }
//
//    private static void readUserJson(String inputLine) {
//        // Read out user attributes for displaying in TextView, ImageView
//
//        List<HashMap<String, String>> results = new ArrayList<>();
//        JSONArray jArray;
//        try {
//            jArray = new JSONArray(inputLine);
//
//            for (int i = 0; i < jArray.length(); i++) {
//                HashMap<String, String> hm = new HashMap<>();
//
//                JSONObject json_data = jArray.getJSONObject(i);
//
//                hm.put("display_name", json_data.getString("display_name"));
//                hm.put("user_email", json_data.getString("user_email"));
//
//                results.add(hm);
//            }
//
//            for (HashMap<String, String> model : results) {
//                System.out.printf("Display Name: %s \nE-mail: %s\n\n", model.get("display_name"), model.get("user_email"));
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }

    // Build string for POST
    private static String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }

    // WRITE TO CACHE -- https://developer.android.com/training/data-storage/files#WriteCacheFileInternal
//    private File getTempFile(Context context, String url) {
//        File file;
//        try {
//            String fileName = Uri.parse(url).getLastPathSegment();
//            file = File.createTempFile(fileName, null, context.getCacheDir());
//        } catch (IOException e) {
//            // Error while creating file
//        }
//        return file;
//    }

    private static void updateUserPoints()
    {
        // CALL PHP -- SQL UPDATE ON ROW WITH user_name
        // THEN update the stored JSON
    }
}
