/*
 * Copyright 2017 Martin Kamp Jensen
 *
 * 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.github.mkjensen.tv.backend;

import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber;

/**
 * Wraps Retrofit's {@link Call} as {@link LiveData}.
 */
class CallLiveData<T> extends LiveData<T> implements Callback<T> {

  private final Call<T> call;

  private CallLiveData(@NonNull Call<T> call) {

    this.call = call;
  }

  /**
   * Creates a {@link LiveData} wrapper for the specified {@link Call}.
   *
   * @param call the non-{@code null} {@link Call} to wrap
   */
  public static <T> CallLiveData<T> wrap(@NonNull Call<T> call) {

    return new CallLiveData<>(call);
  }

  @Override
  public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {

    if (!response.isSuccessful()) {
      Timber.e("Unsuccessful response for call to [" + call.request().url() + "]: "
          + response.code() + ", " + response.message());
      // TODO: Forward error
    }

    setValue(response.body());
  }

  @Override
  public void onFailure(@NonNull Call<T> call, @NonNull Throwable throwable) {

    Timber.e(throwable, "Failure for call: " + call.request().url());
    // TODO: Forward error
  }


  @Override
  protected void onActive() {

    if (call.isCanceled() || call.isExecuted()) {
      return;
    }

    call.enqueue(this);
  }
}

@@ -1469,46 +1469,52 @@
 .e(%22
-Unsuccessful response for call to %5B%22 +
+onResponse: Call %5B%25s%5D unsuccessful: %25s, %25s%22,
  cal
@@ -1534,28 +1534,9 @@
 rl()
- + %22%5D: %22%0A          +
+,
  res
@@ -1551,17 +1551,19 @@
 de()
- + %22, %22 +
+,%0A         
  res
@@ -1609,26 +1609,112 @@
 d error%0A    
-%7D%0A
+  return;%0A    %7D%0A%0A    Timber.d(%22onResponse: Call %5B%25s%5D successful%22, call.request().url());
 %0A    setValu
@@ -1859,29 +1859,26 @@
 e, %22
-Failure for call: %22 +
+Call %5B%25s%5D failed%22,
  cal
@@ -2025,38 +2025,210 @@
 ()) %7B%0A      
-return;%0A    %7D%0A
+Timber.d(%22onActive: Call %5B%25s%5D is cancelled or has already been executed%22, call.request().url());%0A      return;%0A    %7D%0A%0A    Timber.d(%22onActive: Enqueuing call %5B%25s%5D%22, call.request().url());
 %0A    call.en

Improve logging