package com.nielsen.simplenoidandroid8100.utils;

import android.util.Log;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;

public class GenerateAndFireID {

    private final String TAG = GenerateAndFireID.class.getSimpleName();

    public String generateAndFireID() {

        final String UAID_BASE62_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyz";

        final int UAID_PAYLOAD_LENGTH = 29;

        StringBuilder uaidBuilder = new StringBuilder();


        // create a random number payload as base-62 digits with 29 characters length

        for (int i = 0; i < UAID_PAYLOAD_LENGTH; i++) {

            Random random = new Random();

            int randomIdx = random.nextInt(UAID_BASE62_CHARACTERS.length());

            uaidBuilder.append(UAID_BASE62_CHARACTERS.charAt(randomIdx));

        }


        // add 10 digit timestamp

        uaidBuilder.append((long)(System.currentTimeMillis() / 1000L));

        String uaid = uaidBuilder.toString();

        sendID(uaid);


        return uaid;

    }

    private void sendID(String uaid){

        try {

            URL url = new URL("https://"+uaid+".uaid.imrworldwide.com");


            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            int statusCode = conn.getResponseCode();

            Log.d(TAG, "Response: " + conn.toString());

            if(statusCode == HttpURLConnection.HTTP_OK){

                Log.v(TAG, "Response is OK");
            }

        } catch (MalformedURLException ex) {
            Log.e("Error", Log.getStackTraceString(ex));
        }
        catch (IOException ex) {
            Log.e("Error", Log.getStackTraceString(ex));
        }
    }

}
