package fr.diabhelp.diabhelp.Core;

/**
 * Created by naqued on 28/09/15.
 */
import android.app.ProgressDialog;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import fr.diabhelp.diabhelp.API.Asynctasks.CatalogueAPICallTask;
import fr.diabhelp.diabhelp.API.IApiCallTask;
import fr.diabhelp.diabhelp.API.ResponseModels.ResponseCatalogue;
import fr.diabhelp.diabhelp.Utils.NetworkUtils;
import fr.diabhelp.diabhelp.Models.CatalogModule;
import fr.diabhelp.diabhelp.R;
import fr.diabhelp.diabhelp.Utils.MyToast;

public class CatalogueFragment extends Fragment implements IApiCallTask<ResponseCatalogue> {
    private RecyclerView                _recyclerView;
    private RecyclerView.Adapter        _recAdapter;
    private RecyclerView.LayoutManager  _recLayoutManager;
    private List<CatalogModule>         _modulesList/* = new ArrayList<>()*/;
    private ProgressDialog              _progress;


    //default constructor
    public CatalogueFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        if (NetworkUtils.getConnectivityStatus(getActivity())){
            new CatalogueAPICallTask(getActivity(), this).execute();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_user) {
            return (false);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        MenuItem item=menu.findItem(R.id.action_user);
        item.setVisible(false);
        item.setEnabled(false);
        return ;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.catalogue_fragment, container, false);
        _recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
        _recyclerView.setHasFixedSize(true);
        _recLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
        _recyclerView.setLayoutManager(_recLayoutManager);

        return v;
    }

    private void checkAvailability() {
        List<PackageInfo> packs = getActivity().getPackageManager().getInstalledPackages(0);
        for(int i = 0 ; i < packs.size() ; i++) {
            PackageInfo p = packs.get(i);
            if ((p.packageName.contains("diabhelp") && !p.packageName.contains("diabhelp.diabhelp"))) {
                for (int j = 0 ; j < _modulesList.size() ; j++) {
                    if (_modulesList.get(j).getName().equals(p.applicationInfo.loadLabel(getActivity().getPackageManager()).toString()));
                        //_modulesList.remove(j);
                }
            }
        }
    }

    @Override
    public void onBackgroundTaskCompleted(String s, int type, String action) throws JSONException {}

    @Override
    public void onBackgroundTaskCompleted(ResponseCatalogue response, String action, ProgressDialog progress) {
        _progress = progress;
        CatalogueFragment.Error error = response.getError();
        Integer errorCode = error.getErrorCode();
        if (errorCode != null && errorCode != 0) {
            manageError(response.getError());
        }
        else if (action.equals("getModules")) {
            displayModules(response.getModules());
        }
    }

    private void displayModules(List<CatalogModule> modules) {
        _progress.dismiss();
        _modulesList = modules;
        _recAdapter = new CatalogRecyclerAdapter(_modulesList);
        _recyclerView.setAdapter(_recAdapter);
        Log.i("display module", "nb = " + modules.size());
        checkAvailability();
        _recAdapter.notifyDataSetChanged();
    }

    private void manageError(CatalogueFragment.Error error) {
        _progress.dismiss();
        switch (error) {
            case SERVER_ERROR:{
                MyToast.getInstance().displayWarningMessage(getString(R.string.error_server), Toast.LENGTH_LONG, getActivity());
                Log.e(getClass().getSimpleName(), "Problème survenu lors de la connexion au serveur");
                break;
            }
        }
    }

    public enum  Error
    {
        NONE(0),
        SERVER_ERROR(1);

        private Integer errorCode;

        Error(Integer i) {
            this.errorCode = i;
        }

        public Integer getErrorCode() {
            return this.errorCode;
        }
    }

}

@@ -1539,32 +1539,333 @@
 ionsMenu(true);%0A
+%0A%0A    %7D%0A%0A    // Override this function is a tricks to launch a task only when the user hint the fragment%0A    // cf : PageViewer life cycle%0A    @Override%0A    public void setUserVisibleHint(boolean isVisibleToUser) %7B%0A        super.setUserVisibleHint(isVisibleToUser);%0A        if (isVisibleToUser) %7B%0A    
         if (Netw
@@ -1910,18 +1910,23 @@
 vity()))
+ 
 %7B%0A
+    
         
@@ -1982,24 +1982,98 @@
 .execute();%0A
+            %7D%0A        %7Delse%7B%0A            // fragment is no longer visible%0A
         %7D%0A  
@@ -2062,39 +2062,41 @@
 sible%0A        %7D%0A
-
     %7D%0A%0A
+%0A%0A
     @Override%0A  

fix viewpager load via overriding setUserVisibleHint