package com.AlexanderZaytsev.RNI18n;

import android.os.Build;
import android.os.LocaleList;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;

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

public class RNI18nModule extends ReactContextBaseJavaModule {

  public RNI18nModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @Override
  public String getName() {
    return "RNI18n";
  }

  private String toLanguageTag(Locale locale) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      return locale.toLanguageTag();
    }

    StringBuilder builder = new StringBuilder();
    builder.append(locale.getLanguage());

    if (locale.getCountry() != null) {
      builder.append("-");
      builder.append(locale.getCountry());
    }

    return builder.toString();
  }

  private WritableArray getLocaleList() {
    WritableArray array = Arguments.createArray();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      LocaleList locales = getReactApplicationContext()
          .getResources().getConfiguration().getLocales();

      for (int i = 0; i < locales.size(); i++) {
        array.pushString(this.toLanguageTag(locales.get(i)));
      }
    } else {
      array.pushString(this.toLanguageTag(getReactApplicationContext()
          .getResources().getConfiguration().locale));
    }

    return array;
  }

  @Override
  public Map<String, Object> getConstants() {
    HashMap<String, Object> constants = new HashMap<String,Object>();
    constants.put("languages", this.getLocaleList());
    return constants;
  }

  @ReactMethod
  public void getLanguages(Promise promise) {
    try {
      promise.resolve(this.getLocaleList());
    } catch (Exception e) {
      promise.reject(e);
    }
  }
}

@@ -727,24 +727,44 @@
 e locale) %7B%0A
+    String langTag;%0A
     if (Buil
@@ -822,22 +822,25 @@
 %7B%0A      
-return
+langTag =
  locale.
@@ -861,22 +861,30 @@
 );%0A    %7D
-%0A%0A
+ else %7B%0A 
     
+ 
 StringBu
@@ -920,24 +920,26 @@
 lder();%0A    
+  
 builder.appe
@@ -965,24 +965,26 @@
 ge());%0A%0A    
+ 
+ 
 if (locale.g
@@ -1002,24 +1002,26 @@
  != null) %7B%0A
+  
       builde
@@ -1033,32 +1033,34 @@
 end(%22-%22);%0A      
+  
 builder.append(l
@@ -1084,29 +1084,36 @@
 ));%0A    
+  
 %7D%0A%0A    
-return
+  langTag =
  builder
@@ -1125,16 +1125,170 @@
 ring();%0A
+    %7D%0A    if (langTag.matches(%22%5E(iw%7Cin%7Cji).*%22))%7B%0A      return langTag.replace(%22iw%22,%22he%22).replace(%22in%22,%22id%22).replace(%22ji%22,%22yi%22);%0A    %7D%0A    return langTag;%0A
   %7D%0A%0A  p

fix android generating old language code for ISO 639