package com.anand.geofence.sample;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;


import com.ad.sdk.mtrack.Device_settings;
import com.ad.sdk.mtrack.Utils;
import com.anand.geofence.NotificationUtils;
import com.anand.geofence.model.request.geofence.GeoLocationRequest;
import com.anand.geofence.model.response.geofence.GeoLocationResponse;
import com.anand.geofence.reference.AppSharedpreferences;
import com.anand.geofence.retrofit.ApiClient;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofenceStatusCodes;
import com.google.android.gms.location.GeofencingEvent;
import com.google.gson.Gson;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GeofenceBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "GeofenceBroadcastReceiv";
    ApiClient apiClient;
    Context context;
    //String latitude,longitude;
    private AppSharedpreferences appSharedpreferences;
    private Device_settings device_settings;
    private String time_zone, latitude, user_agent, js, language, osv, app_id, display_height, connection_type, user_id, dmp_id,
            display_width, data_speed, viewer_phone, model, udid, make, longitude, device_type, device_email, screen_width, dpid1, dpid5,
            os, ip, viewer_name, carrier, viewer_email, screen_height, publisher_id, adType,geoId, identifier;

    @Override
    public void onReceive(Context context, Intent intent) {
        apiClient = ApiClient.getInstance();
        appSharedpreferences = AppSharedpreferences.getInstance(context);
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            String errorMessage = GeofenceStatusCodes.getStatusCodeString(geofencingEvent.getErrorCode());
            Log.e(TAG, errorMessage);
            return;
        }

        int geofenceTransition = geofencingEvent.getGeofenceTransition();
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
            Toast.makeText(context, "Entered Location", Toast.LENGTH_SHORT).show();
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
            for (Geofence geofence : triggeringGeofences) {
               latitude = geofence.getRequestId().split(",")[0];
               longitude = geofence.getRequestId().split(",")[1];
               geoId = geofence.getRequestId().split(",")[2];
               identifier = geofence.getRequestId().split(",")[3];
                Log.d(TAG, "Matched Geofence - Latitude: " + latitude + ", Longitude: " + longitude+", GeoId: "+geoId+", Identifier: "+identifier);
            }
            sendLocation(context);
            NotificationUtils.sendGeofenceEnteredNotification((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE), context);

        } else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
            Toast.makeText(context, "Exited geofence area", Toast.LENGTH_SHORT).show();
        } else {
            Log.e(TAG, "Invalid type transition " + geofenceTransition);
        }
    }

    private void sendLocation(Context context) {
        device_settings = new Device_settings(context);
        time_zone = device_settings.timezone;
        user_agent = device_settings.ua;
        js = String.valueOf(device_settings.js_enable);
        language = device_settings.language;
        display_height = String.valueOf(device_settings.display_height);
        connection_type = device_settings.connection_type;
        user_id = "";
        dmp_id = device_settings.getGAID();
        display_width = String.valueOf(device_settings.display_width);
        data_speed = device_settings.data_speed;
        osv = device_settings.os_ver;
        app_id = device_settings.app_id;
        viewer_phone = device_settings.user_phone;
        model = device_settings.model;
        udid = device_settings.android_id;
        make = device_settings.make;
        device_type = device_settings.device_type;
        device_email = device_settings.user_email;
        screen_width = String.valueOf(device_settings.screen_width);
        dpid1 = device_settings.didsha1;
        os = device_settings.os;
        ip = Utils.getLocalIpAddress();
        dpid5 = device_settings.didmd5;
        viewer_name = device_settings.user_name;
        carrier = device_settings.carrier;
        viewer_email = device_settings.user_email;
        screen_height = String.valueOf(device_settings.screen_height);
        //publisher_id = zone_id;

        String publisherId = appSharedpreferences.getString("publisherId");
        String fcmToken = appSharedpreferences.getString("token");
        GeoLocationRequest geoLocationRequest = new GeoLocationRequest();
        geoLocationRequest.setLatitude(latitude);
        geoLocationRequest.setLongitude(longitude);
        geoLocationRequest.setOs("Android");
        geoLocationRequest.setPublisherid(Integer.valueOf(publisherId));
        geoLocationRequest.setDeviceToken(fcmToken);
        geoLocationRequest.setTimezone(time_zone);
//        geoLocationRequest.setUseragent(user_agent);
        geoLocationRequest.setUseragent("");
        geoLocationRequest.setJs(js);
        geoLocationRequest.setLanguage(language);
        geoLocationRequest.setDisplayheight(display_height);
        geoLocationRequest.setConnectiontype(connection_type);
        geoLocationRequest.setDmpId(dmp_id);
        geoLocationRequest.setUserid(user_id);
        geoLocationRequest.setDisplaywidth(display_width);
        geoLocationRequest.setDataSpeed(data_speed);
        geoLocationRequest.setOsv(Integer.valueOf(osv));
        geoLocationRequest.setAppId(app_id);
        geoLocationRequest.setViewerPhone(Long.valueOf(viewer_phone));
        geoLocationRequest.setModel(model);
        geoLocationRequest.setUdid(udid);
        geoLocationRequest.setMake(make);
        geoLocationRequest.setDeviceType(device_type);
        geoLocationRequest.setDeviceEmail(device_email);
        geoLocationRequest.setScreenwidth(Integer.valueOf(screen_width));
        geoLocationRequest.setDpidsha1(dpid1);
        geoLocationRequest.setIp(ip);
        geoLocationRequest.setDpidmd5(dpid5);
        geoLocationRequest.setViewerName(viewer_name);
        geoLocationRequest.setCarrier(carrier);
        geoLocationRequest.setViewerEmail(viewer_email);
        geoLocationRequest.setScreenheight(Integer.valueOf(screen_height));
        geoLocationRequest.setGeoid(geoId);
        geoLocationRequest.setIdentifier(identifier);
        geoLocationRequest.setViewerage(20);
        geoLocationRequest.setViewergender("female");

        Gson gson2 = new Gson();
        String json2 = gson2.toJson(geoLocationRequest);
        Log.i("geoLocationRequest345", json2);

        apiClient.getApiInterface().sentGeoLocation(geoLocationRequest).enqueue(new Callback<GeoLocationResponse>() {
            @Override
            public void onResponse(Call<GeoLocationResponse> call, Response<GeoLocationResponse> response) {
                GeoLocationResponse geoLocationResponse = response.body();
               /* assert response.body() != null;
                if (response.body().getAds() != null){
                   Log.i("clickurl","clickurl : "+geoLocationResponse.getAds().getClickUrl());
                   Log.i("impressionUrl","impressionUrl : "+geoLocationResponse.getAds().getImpUrl());
                   appSharedpreferences.saveString("clickurl",response.body().getAds().getClickUrl());
                   String impressionUrl = geoLocationResponse.getAds().getImpUrl();
                   new ImpressionTask().execute(impressionUrl);
               }*/

            }

            @Override
            public void onFailure(Call<GeoLocationResponse> call, Throwable t) {

            }
        });
   }

    public static String extractGeofenceId(String input) {
        String pattern = "id:([^ ]+)";
        java.util.regex.Pattern r = java.util.regex.Pattern.compile(pattern);
        java.util.regex.Matcher m = r.matcher(input);
        if (m.find()) {
            return m.group(1);
        }
        return "";
    }
}
