/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pyamsoft.powermanager.dagger.manager;

import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import com.pyamsoft.powermanager.app.manager.Manager;
import javax.inject.Inject;
import rx.Observable;
import rx.Scheduler;
import rx.Subscription;
import rx.subscriptions.Subscriptions;
import timber.log.Timber;

abstract class ManagerBase implements Manager {

  @NonNull private final ManagerInteractor interactor;
  @NonNull private final Scheduler subscribeScheduler;
  @NonNull private final Scheduler observerScheduler;
  @NonNull private Subscription setSubscription = Subscriptions.empty();
  @NonNull private Subscription unsetSubscription = Subscriptions.empty();

  ManagerBase(@NonNull ManagerInteractor interactor, @NonNull Scheduler subscribeScheduler,
      @NonNull Scheduler observerScheduler) {
    this.interactor = interactor;
    this.subscribeScheduler = subscribeScheduler;
    this.observerScheduler = observerScheduler;
  }

  void unsubSet() {
    if (!setSubscription.isUnsubscribed()) {
      setSubscription.unsubscribe();
    }
  }

  void unsubUnset() {
    if (!unsetSubscription.isUnsubscribed()) {
      unsetSubscription.unsubscribe();
    }
  }

  @CheckResult @NonNull Observable<Boolean> baseObservable() {
    return interactor.cancelJobs().flatMap(cancelled -> {
      if (cancelled) {
        Timber.d("Is Managed?");
        return interactor.isManaged();
      } else {
        Timber.w("Cancel jobs failed, return empty");
        return Observable.empty();
      }
    });
  }

  @Override public void queueSet() {
    unsubSet();
    baseObservable().flatMap(managed -> {
      if (managed) {
        Timber.d("Is original state enabled?");
        return interactor.isOriginalStateEnabled();
      } else {
        Timber.w("Is not managed, return empty");
        return Observable.empty();
      }
    }).subscribeOn(subscribeScheduler).observeOn(observerScheduler).subscribe(originalState -> {
      // Technically can ignore this as if we are here we are non-empty
      // If we are non empty it means we pass the test
      if (originalState) {
        interactor.queueEnableJob();
      }
    }, throwable -> Timber.e(throwable, "onError queueSet"), this::unsubSet);
  }

  @Override public void queueUnset(boolean deviceCharging) {
    unsubUnset();
    baseObservable().flatMap(managed -> {
      if (managed) {
        Timber.d("Is ignore while charging?");
        return interactor.isIgnoreWhileCharging();
      } else {
        Timber.w("Is not managed, return empty");
        return Observable.empty();
      }
    }).map(ignoreWhileCharging -> {
      Timber.d("Is device currently charging?");
      return ignoreWhileCharging && deviceCharging;
    }).flatMap(ignore -> {
      if (ignore) {
        Timber.w("Set to ignore on charging, and device is charging, return empty");
        return Observable.empty();
      } else {
        Timber.d("Is not ignored while charging, or is not charging");
        return interactor.isEnabled();
      }
    }).map(enabled -> {
      Timber.d("Set original state enabled: %s", enabled);
      interactor.setOriginalStateEnabled(enabled);
      return enabled;
    }).subscribeOn(subscribeScheduler).observeOn(observerScheduler).subscribe(isEnabled -> {
      // Only queue a disable job if the radio begins the cycle enabled
      if (isEnabled) {
        interactor.queueDisableJob();
      }
    }, throwable -> Timber.e(throwable, "onError queueUnset"), this::unsubUnset);
  }

  @Override public void cleanup() {
    interactor.destroy();
    unsubSet();
    unsubUnset();
  }
}

@@ -797,36 +797,8 @@
 er;%0A
-import javax.inject.Inject;%0A
 impo
@@ -3006,29 +3006,30 @@
 %22Is 
-ignore while charging
+original state enabled
 ?%22);
@@ -3061,27 +3061,15 @@
 r.is
-IgnoreWhileCharging
+Enabled
 ();%0A
@@ -3187,35 +3187,23 @@
  %7D).map(
-ignoreWhileCharging
+enabled
  -%3E %7B%0A  
@@ -3220,91 +3220,122 @@
 .d(%22
-Is device currently charging?%22);%0A      return ignoreWhileCharging && deviceCharging
+Set original state enabled: %25s%22, enabled);%0A      interactor.setOriginalStateEnabled(enabled);%0A      return enabled
 ;%0A  
@@ -3347,22 +3347,23 @@
 flatMap(
-ignore
+enabled
  -%3E %7B%0A  
@@ -3370,22 +3370,23 @@
     if (
-ignore
+enabled
 ) %7B%0A    
@@ -3400,25 +3400,21 @@
 ber.
-w(%22Set to
+d(%22Is
  ignore 
 on c
@@ -3413,92 +3413,74 @@
 ore 
-on charging, and device is charging, return empty%22);%0A        return Observable.empty
+while charging?%22);%0A        return interactor.isIgnoreWhileCharging
 ();%0A
@@ -3505,25 +3505,25 @@
      Timber.
-d
+w
 (%22Is not ign
@@ -3523,89 +3523,64 @@
 not 
-ignored while charging, or is not charging%22);%0A        return interactor.isEnabled
+managed, return empty%22);%0A        return Observable.empty
 ();%0A
@@ -3590,39 +3590,51 @@
    %7D%0A    %7D).map(
-enabled
+ignoreWhileCharging
  -%3E %7B%0A      Timb
@@ -3643,122 +3643,91 @@
 .d(%22
-Set original state enabled: %25s%22, enabled);%0A      interactor.setOriginalStateEnabled(enabled);%0A      return enabled
+Is device currently charging?%22);%0A      return ignoreWhileCharging && deviceCharging
 ;%0A  
@@ -3803,24 +3803,21 @@
 scribe(i
-sEnabled
+gnore
  -%3E %7B%0A  
@@ -3865,30 +3865,20 @@
 dio 
-begins the cycle enabl
+is not ignor
 ed%0A 
@@ -3886,25 +3886,23 @@
     if (
-isEnabled
+!ignore
 ) %7B%0A    

Check enabled state before charging for disable jobs