package com.tasomaniac.muzei.comiccovers;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.google.android.apps.muzei.api.provider.Artwork;
import com.google.android.apps.muzei.api.provider.ProviderContract;
import com.tasomaniac.muzei.comiccovers.model.Comic;
import com.tasomaniac.muzei.comiccovers.model.ComicVineResponse;
import com.tasomaniac.muzei.comiccovers.util.IOUtil;
import timber.log.Timber;

import java.io.IOException;
import java.util.Random;

public class ComicVineWorker extends Worker {

    private static final String NUM_OF_TOTAL_RESULTS = "number_of_total_results";
    private static final String COMIC_ID = "comic_id";

    private final Random random = new Random();
    private final SharedPreferences prefs;

    private int max_size;

    public ComicVineWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);

        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        max_size = prefs.getInt(NUM_OF_TOTAL_RESULTS, Config.NUM_TOTAL_RESULTS);
    }

    @NonNull @Override public Result doWork() {
        ComicVineService service = ComicVineServiceFactory.createComicVineService(getApplicationContext());

        try {
            Comic comic = getNextComic(service);

            if (comic == null) {
                return Result.FAILURE;
            }

            ProviderContract.Artwork.addArtwork(
                    getApplicationContext(),
                    BuildConfig.COMIC_VINE_AUTHORITY,
                    toArtwork(comic));
            return Result.SUCCESS;
        } catch (IOException e) {
            Timber.e(e, "No internet connection");
            return Result.RETRY;
        }
    }

    private Comic getNextComic(final ComicVineService service) throws IOException {
        String currentToken = prefs.getString(COMIC_ID, null);

        String offset = String.valueOf(random.nextInt(max_size));
        ComicVineResponse response = service.getIssues(offset).execute().body();

        if (response == null || response.getResults() == null || response.getResults().isEmpty()) {
            Timber.d("Error getting the image %s", offset);
            return null;
        }

        max_size = response.getNumberOfTotalResult();
        prefs.edit().putInt(NUM_OF_TOTAL_RESULTS, max_size).apply();

        Comic comic = response.getResults().get(0);
        String newToken = String.valueOf(comic.getId());
        boolean isContentValid = IOUtil.checkContentType(
                getApplicationContext(),
                comic.getImage().getSuperUrl()
        );
        if (!newToken.equals(currentToken) && isContentValid) {
            return comic;
        } else {
            return getNextComic(service);
        }
    }

    private Artwork toArtwork(Comic comic) {
        StringBuilder name = new StringBuilder();
        if (comic.getVolume().getName() != null) {
            name.append(comic.getVolume().getName());
        }
        if (comic.getName() != null) {
            if (name.length() > 0) {
                name.append(" | ");
            }
            name.append(comic.getName());
        }

        return new Artwork.Builder()
                .title(name.toString())
                .byline("Data provided by © ComicVine.")
                .persistentUri(Uri.parse(comic.getImage().getSuperUrl()))
                .token(String.valueOf(comic.getId()))
                .webUri(Uri.parse(comic.getSiteDetailUrl()))
                .build();
    }

    static void enqueue() {
        WorkManager.getInstance().enqueue(
                new OneTimeWorkRequest.Builder(ComicVineWorker.class)
                        .setConstraints(new Constraints.Builder()
                                .setRequiredNetworkType(NetworkType.CONNECTED)
                                .build()
                        )
                        .build()
        );
    }
}

@@ -3520,32 +3520,401 @@
 ());%0A        %7D%0A%0A
+        StringBuilder byline = new StringBuilder();%0A        if (comic.getIssueNumber() != 0) %7B%0A            byline.append(%22Issue #%22).append(comic.getIssueNumber());%0A        %7D%0A        if (comic.getCoverDate() != null) %7B%0A            if (byline.length() %3E 0) %7B%0A                byline.append(%22 %7C %22);%0A            %7D%0A            byline.append(comic.getCoverDate());%0A        %7D%0A%0A
         return n
@@ -3998,16 +3998,64 @@
 .byline(
+byline.toString())%0A                .attribution(
 %22Data pr

Add byline