package com.feedbackreactnativesdk;

import android.util.Log;

import com.facebook.react.bridge.ReadableMap;

import java.util.HashMap;
import java.util.Map;

import co.pisano.feedback.data.model.PisanoCustomer;

public class PisanoCustomerHelper {

  static final String TAG = "PisanoCustomerHelper";

  static PisanoCustomer convertToPisanoCustomer(ReadableMap customerMap) {
    if (customerMap == null) {
      return null;
    }

    try {
      HashMap<String, Object> map = customerMap.toHashMap();

      String name = getStringValue(map, "name");
      String email = getStringValue(map, "email");
      String phoneNumber = getStringValue(map, "phoneNumber", "phone_number");
      String externalId = getStringValue(map, "externalId", "external_id");

      HashMap<String, Object> customAttributes = null;
      Object attrsRaw = map.containsKey("customAttributes") ? map.get("customAttributes")
          : map.get("custom_attrs");
      if (attrsRaw instanceof Map) {
        customAttributes = new HashMap<>((Map<String, Object>) attrsRaw);
      }

      if (name == null && email == null && phoneNumber == null
          && externalId == null && customAttributes == null) {
        return null;
      }

      return new PisanoCustomer(name, externalId, email, phoneNumber, customAttributes);
    } catch (Exception e) {
      Log.e(TAG, "convertToPisanoCustomer failed: " + e.toString());
      return null;
    }
  }

  public static HashMap<String, String> convertReadableMapToHashMap(ReadableMap readableMap) {
    try {
      Map<String, Object> objectMap = readableMap.toHashMap();
      HashMap<String, String> stringMap = new HashMap<>();

      for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
        stringMap.put(entry.getKey(), String.valueOf(entry.getValue()));
      }

      return stringMap;
    } catch (Exception e) {
      Log.e(TAG, e.toString());
      return null;
    }
  }

  private static String getStringValue(HashMap<String, Object> map, String... keys) {
    for (String key : keys) {
      Object value = map.get(key);
      if (value instanceof String && !((String) value).isEmpty()) {
        return (String) value;
      }
    }
    return null;
  }
}
