/*
 * Copyright 2015 Priyesh Patel
 *
 * 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.chromium.fontinstaller.core;

import android.content.Context;
import android.os.Handler;

import com.chromium.fontinstaller.BusProvider;
import com.chromium.fontinstaller.events.DownloadCompleteEvent;
import com.chromium.fontinstaller.models.Font;
import com.chromium.fontinstaller.models.FontPackage;
import com.chromium.fontinstaller.models.Style;
import com.koushikdutta.ion.Ion;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import timber.log.Timber;

/**
 * Created by priyeshpatel on 15-02-07.
 */
public class FontDownloader {

    private FontPackage fontPackage;
    private Context context;
    private enum CompletionStatus {INCOMPLETE, COMPLETE, ERROR}
    private HashMap<Font, CompletionStatus> hashMap = new HashMap<>();

    public FontDownloader(FontPackage fontPackage, Context context) {
        this.fontPackage = fontPackage;
        this.context = context;

        createCacheDir(fontPackage);
    }

    public FontDownloader(Context context) {
        this.context = context;
    }

    public void downloadAll() {
        for (Font font : fontPackage.getFontList()) {
            hashMap.put(font, CompletionStatus.INCOMPLETE);

            File file = new File(context.getExternalCacheDir() + File.separator +
                    fontPackage.getNameFormatted() + File.separator + font.getName());

            Ion.with(context).load(font.getUrl()).write(file)
                    .setCallback((e, downloadedFile) -> {
                        if (e != null) {
                            Timber.i("Download failed " + e);
                            hashMap.put(font, CompletionStatus.ERROR);
                        } else {
                            hashMap.put(font, CompletionStatus.COMPLETE);
                            Timber.i("Download successful " + downloadedFile);
                        }
                    });
        }
        checkCompletion();
    }

    public void downloadFromList(List<FontPackage> fontPackages, Style style) {
        for (FontPackage fontPackage : fontPackages) {
            createCacheDir(fontPackage);

            hashMap.put(fontPackage.getFont(style), CompletionStatus.INCOMPLETE);

            File file = new File(context.getExternalCacheDir() + File.separator +
                    fontPackage.getNameFormatted() + File.separator + style.getLocalName());

            Ion.with(context).load(fontPackage.getFont(style).getUrl()).write(file)
                    .setCallback((e, downloadedFile) -> {
                        if (e != null) {
                            Timber.i("Download failed " + e);
                            hashMap.put(fontPackage.getFont(style), CompletionStatus.ERROR);
                        } else {
                            Timber.i("Download successful " + downloadedFile);
                            hashMap.put(fontPackage.getFont(style), CompletionStatus.COMPLETE);
                        }
                    });
        }
        checkCompletion();
    }

    private void createCacheDir(FontPackage fontPackage) {
        File dir = new File(context.getExternalCacheDir() + File.separator + fontPackage.getNameFormatted());
        dir.mkdirs();
    }

    private void checkCompletion() {
        new Handler().postDelayed(() -> {
            if (hashMap.containsValue(CompletionStatus.INCOMPLETE)) checkCompletion();
            else evaluateCompletionStatus();
        }, 500);
    }

    private void evaluateCompletionStatus() {
        if (hashMap.containsValue(CompletionStatus.ERROR)) {
            Timber.i("Download failed");
            BusProvider.getInstance().post(new DownloadCompleteEvent(false));
        } else {
            Timber.i("Download success");
            BusProvider.getInstance().post(new DownloadCompleteEvent(true));
        }
    }
}
@@ -1946,32 +1946,70 @@
 nt.getName());%0A%0A
+            if (!file.exists()) %7B%0A    
             Ion.
@@ -2066,32 +2066,36 @@
                 
+    
 .setCallback((e,
@@ -2108,32 +2108,36 @@
 oadedFile) -%3E %7B%0A
+    
                 
@@ -2181,32 +2181,36 @@
                 
+    
 Timber.i(%22Downlo
@@ -2219,32 +2219,36 @@
  failed %22 + e);%0A
+    
                 
@@ -2294,32 +2294,36 @@
 nStatus.ERROR);%0A
+    
                 
@@ -2359,32 +2359,36 @@
                 
+    
 hashMap.put(font
@@ -2409,32 +2409,36 @@
 atus.COMPLETE);%0A
+    
                 
@@ -2516,34 +2516,42 @@
                 
+   
+ 
 %7D%0A
+    
                 
@@ -2550,32 +2550,129 @@
             %7D);%0A
+            %7D else %7B%0A                hashMap.put(font, CompletionStatus.COMPLETE);%0A            %7D%0A
         %7D%0A      
@@ -3127,32 +3127,70 @@
 tLocalName());%0A%0A
+            if (!file.exists()) %7B%0A    
             Ion.
@@ -3269,32 +3269,36 @@
                 
+    
 .setCallback((e,
@@ -3311,32 +3311,36 @@
 oadedFile) -%3E %7B%0A
+    
                 
@@ -3384,32 +3384,36 @@
                 
+    
 Timber.i(%22Downlo
@@ -3422,32 +3422,36 @@
  failed %22 + e);%0A
+    
                 
@@ -3543,32 +3543,36 @@
                 
+   
+ 
 %7D else %7B%0A       
@@ -3556,32 +3556,36 @@
        %7D else %7B%0A
+    
                 
@@ -3667,32 +3667,36 @@
                 
+    
 hashMap.put(font
@@ -3763,34 +3763,42 @@
                 
+   
+ 
 %7D%0A
+    
                 
@@ -3797,32 +3797,151 @@
             %7D);%0A
+            %7D else %7B%0A                hashMap.put(fontPackage.getFont(style), CompletionStatus.COMPLETE);%0A            %7D%0A
         %7D%0A      
@@ -4078,32 +4078,48 @@
 rnalCacheDir() +
+%0A               
  File.separator 

Load from disk if fonts exist