package io.rumors.reactnativesettings.listeners;

import android.content.Intent;
import android.content.Context;
import android.view.accessibility.CaptioningManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Build;

import io.rumors.reactnativesettings.handlers.CaptioningSettingsHandler;
import io.rumors.reactnativesettings.Constants;

import java.util.concurrent.CountDownLatch;


public class CaptioningChangeListener extends CaptioningManager.CaptioningChangeListener {
  private Context mContext;

  private CaptioningManager mCaptioningManager;

  private CaptioningManager getCaptioningManager() {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
      return (CaptioningManager) mContext.getSystemService(Context.CAPTIONING_SERVICE);
    } else {
      // Android <= 5 bug workaround
      // https://github.com/evernote/android-job/issues/48#issuecomment-221789418
      final CountDownLatch latch = new CountDownLatch(1);

      Handler handler = new Handler(Looper.getMainLooper());
      handler.post(new Runnable() {
          @Override
          public void run() {
              mCaptioningManager = (CaptioningManager) mContext.getSystemService(Context.CAPTIONING_SERVICE);
              latch.countDown();
          }
      });
  
      try {
          latch.await();
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  
      return mCaptioningManager;
    }
  }

  public CaptioningChangeListener(Context context) {
    this.mContext = context;
    CaptioningManager captioningManager = getCaptioningManager();
    captioningManager.addCaptioningChangeListener(this);
  }

  @Override
  public void onEnabledChanged(boolean enabled) {
    String captioning = (new CaptioningSettingsHandler(mContext)).getSetting();

    Intent i = new Intent(Constants.CAPTIONING_CHANGED);
    i.putExtra(Constants.CAPTIONING_SETTINGS, captioning);
    mContext.sendBroadcast(i);
  }
}

@@ -405,17 +405,16 @@
 Latch;%0A%0A
-%0A
 public c
@@ -658,16 +658,17 @@
 DK_INT %3E
+=
  Build.V
@@ -684,16 +684,9 @@
 DES.
-LOLLIPOP
+M
 ) %7B%0A
@@ -1069,18 +1069,16 @@
         
-  
 @Overrid
@@ -1079,18 +1079,16 @@
 verride%0A
-  
         
@@ -1103,28 +1103,24 @@
 oid run() %7B%0A
-    
           mC
@@ -1219,28 +1219,24 @@
 ;%0A          
-    
 latch.countD
@@ -1238,26 +1238,24 @@
 ountDown();%0A
-  
         %7D%0A  
@@ -1262,19 +1262,17 @@
     %7D);%0A
-  
 %0A
+
       tr
@@ -1275,18 +1275,16 @@
   try %7B%0A
-  
         
@@ -1294,24 +1294,24 @@
 ch.await();%0A
+
       %7D catc
@@ -1335,26 +1335,24 @@
 eption e) %7B%0A
-  
         e.pr
@@ -1368,24 +1368,24 @@
 race();%0A
+
       %7D%0A
   %0A     
@@ -1376,18 +1376,16 @@
       %7D%0A
-  
 %0A      r

use getSystemService workaround for versions < Android 6 (#45)