package openfoodfacts.github.scrachx.openfood.views;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;

import com.fasterxml.jackson.core.type.TypeReference;

import net.steamcrafted.loadtoast.LoadToast;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import openfoodfacts.github.scrachx.openfood.R;
import openfoodfacts.github.scrachx.openfood.models.Additive;
import openfoodfacts.github.scrachx.openfood.models.FoodAPIRestClientUsage;
import openfoodfacts.github.scrachx.openfood.utils.JsonUtils;

public class SplashActivity extends BaseActivity {

    private SharedPreferences settings;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        settings = getSharedPreferences("prefs", 0);

        boolean firstRun = settings.getBoolean("firstRun", true);

        boolean errorAdditives = settings.getBoolean("errorAdditives", true);
        boolean errorAllergens = settings.getBoolean("errorAllergens", true);

        if(!errorAdditives && !errorAllergens) {
            settings.edit()
                    .putBoolean("firstRun", false)
                    .apply();
            firstRun = false;
        }

        if (!firstRun) {
            Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(mainIntent);
            finish();
        } else {
            new GetJson(this).execute();
        }
    }

    private class GetJson extends AsyncTask<Void, Integer, Boolean> {

        private Context context;
        private LoadToast lt;

        public GetJson(Context ctx) {
            context = ctx;
            lt = new LoadToast(ctx);
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            lt.setText(context.getString(R.string.toast_retrieving));
            lt.setBackgroundColor(context.getResources().getColor(R.color.indigo_600));
            lt.setTextColor(context.getResources().getColor(R.color.white));
            lt.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            boolean result = true;
            boolean errorAdditives = settings.getBoolean("errorAdditives", true);

            if (!errorAdditives) {
                return result;
            }

            String additivesFile;
            switch (Locale.getDefault().getLanguage()) {
                case "fr":
                    additivesFile = "additives_fr.json";
                    break;
                case "en":
                default:
                    additivesFile = "additives_en.json";
                    break;
            }

            InputStream is = null;
            try {
                is = getAssets().open(additivesFile);
                List<Additive> frenchAdditives = JsonUtils.readFor(new TypeReference<List<Additive>>() {})
                        .readValue(is);
                for (Additive additive : frenchAdditives) {
                    additive.save();
                }
            } catch (IOException e) {
                //TODO handle issue
                result = false;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e1) {
                        // TODO Handle issue
                    }
                }
            }

            return result;
        }

        @Override
        protected void onPostExecute(final Boolean result) {
            super.onPostExecute(result);
            final SharedPreferences.Editor editor = settings.edit();
            boolean errorAllergens = settings.getBoolean("errorAllergens", true);
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
            if (isConnected) {
                if (errorAllergens) {
                    FoodAPIRestClientUsage api = new FoodAPIRestClientUsage(getString(R.string.openfoodUrl));
                    api.getAllergens(new FoodAPIRestClientUsage.OnAllergensCallback() {
                        @Override
                        public void onAllergensResponse(boolean value) {
                            if (result && value) {
                                lt.success();
                                editor.putBoolean("firstRun", false);
                            }
                            if(!value){
                                lt.error();
                                editor.putBoolean("errorAllergens", true);
                            } else {
                                editor.putBoolean("errorAllergens", false);
                            }

                            editor.apply();

                            Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
                            startActivity(mainIntent);
                            finish();
                        }
                    });
                }
            } else {
                if (!result) {
                    lt.error();
                    editor.putBoolean("errorAdditives", true);
                    editor.apply();
                } else {
                    editor.putBoolean("errorAdditives", false);
                    editor.apply();
                }
                Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(mainIntent);
                finish();
            }
        }
    }
}
@@ -278,16 +278,41 @@
 .Bundle;
+%0Aimport android.util.Log;
 %0A%0Aimport
@@ -1732,24 +1732,97 @@
 Boolean%3E %7B%0A%0A
+        private static final String ADDITIVE_IMPORT = %22ADDITIVE_IMPORT%22;%0A
         priv
@@ -3402,58 +3402,114 @@
     
-//TODO handle issue%0A                result = false
+result = false;%0A                Log.e(ADDITIVE_IMPORT, %22Unable to import additives from %22 + additivesFile)
 ;%0A  
@@ -3701,28 +3701,86 @@
     
-// TODO Handle issue
+Log.e(ADDITIVE_IMPORT, %22Unable to close the inputstream of %22 + additivesFile);
 %0A   

add logger for the splashActivity