Proyectos de Subversion Android Microlearning - Inconcert

Rev

Autoría | Ultima modificación | Ver Log |

package com.cesams.twogetskills.inconcert.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.cesams.twogetskills.inconcert.Constants;
import com.cesams.twogetskills.inconcert.R;
import com.cesams.twogetskills.adapter.MyCapsulesAdapter;
import com.cesams.twogetskills.inconcert.dao.CapsuleDao;
import com.cesams.twogetskills.inconcert.dao.ProgressDao;
import com.cesams.twogetskills.inconcert.dao.SlideDao;
import com.cesams.twogetskills.inconcert.entity.Capsule;
import com.cesams.twogetskills.inconcert.entity.Progress;
import com.cesams.twogetskills.inconcert.entity.Slide;
import com.cesams.twogetskills.inconcert.library.ImageService;
import com.cesams.twogetskills.inconcert.skeleton.ITwoGetSkills;
import com.cesams.twogetskills.inconcert.viewmodel.MyCapsulesInProgressViewModel;
import com.cesams.twogetskills.inconcert.viewmodel.MyCapsulesViewModel;
import com.google.android.material.tabs.TabLayout;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;



public class MyCapsulesFragment extends Fragment implements MyCapsulesAdapter.ClickListener, LifecycleOwner {

    private ITwoGetSkills iTwoGetSkills;
    private TextView textViewHelloUsername;
    private EditText editTextSearch;
    private TextView textViewWelcome;
    private RecyclerView recyclerViewCapsules;
    private TabLayout tabLayout;
    private MyCapsulesAdapter myCapsulesAdapter;
    private TextView textViewListingEmpty;
    private MyCapsulesViewModel myCapsulesViewModel;
    private MyCapsulesInProgressViewModel myCapsulesInProgressViewModel;

    private View cardView;
    private TextView cardTextViewStatus;
    private TextView cardTextViewTitle;
    private ProgressBar cardProgressBar;
    private TextView cardTextViewProgress;
    private ImageView cardImageView;
    private Button cardButtonContinue;

    private DecimalFormat mDecimalFormat;


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

        this.mDecimalFormat = new DecimalFormat("#.##");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        iTwoGetSkills = (ITwoGetSkills) getActivity();


        View view = inflater.inflate(R.layout.fragment_my_capsules, container, false);
        textViewHelloUsername =view.findViewById(R.id.fragment_my_capsules_textview_hello_username);


        String helloUsername = StringUtils.replace(requireActivity().getString(R.string.my_capsules_hello), "%", iTwoGetSkills.getPreference().getFirstName());
        textViewHelloUsername .setText(helloUsername);

        textViewListingEmpty = view.findViewById(R.id.fragment_my_capsules_textview_listing_empty);
        textViewWelcome= view.findViewById(R.id.fragment_my_capsules_textview_welcome);
        editTextSearch=view.findViewById(R.id.fragment_my_capsules_edit_text_search);
        cardView = view.findViewById(R.id.fragment_my_capsules_include_cardview);

        //Tarjeta Principal

        cardTextViewStatus = view.findViewById(R.id.cardview_item_textview_status);
        cardTextViewTitle = view.findViewById(R.id.cardview_item_textview_title);
        cardImageView = view.findViewById(R.id.cardview_item_imageview);
        cardProgressBar = view.findViewById(R.id.cardview_item_progressbar);
        cardTextViewProgress = view.findViewById(R.id.cardview_item_textview_progress);
        cardButtonContinue = view.findViewById(R.id.cardview_item_button_continue);
        cardButtonContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUtils.isEmpty(myCapsulesInProgressViewModel.getCapsule().getTopicUuid()) || !StringUtils.isEmpty(myCapsulesInProgressViewModel.getCapsule().getUuid())) {
                    iTwoGetSkills.changeCapsuleActiveSourceNavigationMyCapsules(myCapsulesInProgressViewModel.getCapsule().getTopicUuid(), myCapsulesInProgressViewModel.getCapsule().getUuid());

                }
            }
        });



        myCapsulesViewModel = new ViewModelProvider(requireActivity()).get(MyCapsulesViewModel.class);
        myCapsulesAdapter = new MyCapsulesAdapter(requireActivity(), myCapsulesViewModel.getCapsuleArrayList());
        myCapsulesAdapter.setClickListener(this);

        Observer<ArrayList<Capsule>> myCapsuleListUpdateObserver = new Observer<ArrayList<Capsule>>() {
            @Override
            public void onChanged(ArrayList<Capsule> capsuleList) {
                myCapsulesAdapter.notifyDataSetChanged();
            }
        };

        myCapsulesViewModel.getCapsuleMutableLiveData().observe(requireActivity(), myCapsuleListUpdateObserver);


        myCapsulesInProgressViewModel = new ViewModelProvider(requireActivity()).get(MyCapsulesInProgressViewModel.class);
        Observer<Capsule> myCapsuleInProgressUpdateObserver = new Observer<Capsule>() {
            @Override
            public void onChanged(Capsule capsuleInProgress) {
                if (capsuleInProgress == null || StringUtils.isEmpty(capsuleInProgress.getUuid()))  {
                    cardTextViewStatus.setText(getContext().getString(R.string.my_capsules_capsule_in_progress_not_found));
                    cardTextViewTitle.setText("");
                    cardProgressBar.setProgress(0);
                    cardTextViewProgress.setText("0 %");
                    cardButtonContinue.setVisibility(View.GONE);
                } else {

                    String title = StringUtils.trim(capsuleInProgress.getName());
                    title = title.length() > Constants.TITLE_MAX_LENGTH ? StringUtils.substring(title, 0, Constants.TITLE_MAX_LENGTH) + "...": title;

                    cardTextViewStatus.setText(getContext().getString(R.string.my_capsules_capsule_in_progress_found));
                    cardTextViewTitle.setText(title);
                    cardProgressBar.setProgress((int) capsuleInProgress.getProgress());
                    cardTextViewProgress.setText(mDecimalFormat.format(capsuleInProgress.getProgress()) + " %");

                    cardButtonContinue.setVisibility(View.VISIBLE);

                    ImageService.retrieve(getContext(), capsuleInProgress.getImage(), cardImageView);
                }
            }
        };

        myCapsulesInProgressViewModel.getCapsuleMutableLiveData().observe(requireActivity(), myCapsuleInProgressUpdateObserver);




        tabLayout = view.findViewById(R.id.fragment_my_capsules_tabLayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                String search = "";
                if (editTextSearch != null) {
                    search = StringUtils.trimToEmpty(editTextSearch.getText().toString());
                }

                int tabPosition = Constants.MY_CAPSULES_TAB_PENDING;
                if (tabLayout != null) {
                    tabPosition = tabLayout.getSelectedTabPosition();
                }


                loadData(tabPosition, search);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        editTextSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus)  {
                    cardView.setVisibility(View.GONE);
                    textViewHelloUsername.setVisibility(View.GONE);
                    textViewWelcome.setVisibility(View.GONE);
                }

            }
        });

        editTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String search = "";
                if (editTextSearch != null) {
                    search = StringUtils.trimToEmpty(editTextSearch.getText().toString());
                }

                int tabPosition = Constants.MY_CAPSULES_TAB_PENDING;
                if (tabLayout != null) {
                    tabPosition = tabLayout.getSelectedTabPosition();
                }


                loadData(tabPosition, search);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        GridLayoutManager recyclerViewCapsulesLayout = new GridLayoutManager(getContext(),1,GridLayoutManager.VERTICAL, false);
        recyclerViewCapsules = view.findViewById(R.id.fragment_my_capsules_listing_capsules);
        recyclerViewCapsules.setLayoutManager(recyclerViewCapsulesLayout);
        recyclerViewCapsules.setAdapter(myCapsulesAdapter);
        recyclerViewCapsules.setOnFlingListener(new RecyclerView.OnFlingListener() {
            @Override
            public boolean onFling(int velocityX, int velocityY) {
            if (recyclerViewCapsules.canScrollVertically(-1) ) {
                cardView.setVisibility(View.GONE);
                textViewHelloUsername.setVisibility(View.GONE);
                textViewWelcome.setVisibility(View.GONE);
            } else {
                cardView.setVisibility(View.VISIBLE);
                textViewHelloUsername.setVisibility(View.VISIBLE);
                textViewWelcome.setVisibility(View.VISIBLE);
            }

            return false;
            }
        });


     /*   categorizados.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (!categorizados.canScrollVertically(-1)) {
                 //   Toast.makeText(getActivity(), "Last", Toast.LENGTH_LONG).show();
                    capsulas.setVisibility(View.VISIBLE);
                    username.setVisibility(View.VISIBLE);
                    textowelcome.setVisibility(View.VISIBLE);
                    Log.e("On scroll"," se activa");
                }

            }
        });
*/
        getActivity().runOnUiThread(() -> {


            String message;
            if (myCapsulesViewModel.getCapsuleArrayList().size() == 1) {
                message = getContext().getString(R.string.common_one_capsule_available);
            } else {
                message = getContext().getString(R.string.common_more_capsules_available);
                message = StringUtils.replace(message, "%", String.valueOf(myCapsulesViewModel.getCapsuleArrayList().size()));
            }
            Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();


            iTwoGetSkills.saveNotificationCenter(getContext().getString(R.string.common_content_available),"",message);

        });
        iTwoGetSkills.showNavigationAndToolbar();

        return view;
    }



    @Override
    public void onStart() {
        super.onStart();
        getActivity().runOnUiThread(() -> {

            String search = "";
            if (editTextSearch != null) {
                search = StringUtils.trimToEmpty(editTextSearch.getText().toString());
            }

            int tabPosition = Constants.MY_CAPSULES_TAB_PENDING;
            if (tabLayout != null) {
                tabPosition = tabLayout.getSelectedTabPosition();
            }

            loadData(tabPosition, search);
            loadCapsuleInProgerss();
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().runOnUiThread(() -> {

            String search = "";
            if (editTextSearch != null) {
                search = StringUtils.trimToEmpty(editTextSearch.getText().toString());
            }

            int tabPosition = Constants.MY_CAPSULES_TAB_PENDING;
            if (tabLayout != null) {
                tabPosition = tabLayout.getSelectedTabPosition();
            }

            loadData(tabPosition, search);
            loadCapsuleInProgerss();
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);


        if(!hidden) {

            getActivity().runOnUiThread(() -> {

                String search = "";
                if (editTextSearch != null) {
                    search = StringUtils.trimToEmpty(editTextSearch.getText().toString());
                }

                int tabPosition = Constants.MY_CAPSULES_TAB_PENDING;
                if (tabLayout != null) {
                    tabPosition = tabLayout.getSelectedTabPosition();
                }

                loadData(tabPosition, search);
                loadCapsuleInProgerss();
            });
        }
    }

    private void loadCapsuleInProgerss()
    {
        CapsuleDao capsuleDao = iTwoGetSkills.getDatabase().getCapsuleDao();
        Capsule capsule = capsuleDao.selectLastInProgress(iTwoGetSkills.getPreference().getUserUuid());

        if (capsule == null) {
            myCapsulesInProgressViewModel.getCapsule().setUuid("");
            myCapsulesInProgressViewModel.getCapsule().setTopicUuid("");
            myCapsulesInProgressViewModel.getCapsule().setName("");
            myCapsulesInProgressViewModel.getCapsule().setDescription("");
            myCapsulesInProgressViewModel.getCapsule().setPosition(0);
            myCapsulesInProgressViewModel.getCapsule().setImage("");
            myCapsulesInProgressViewModel.getCapsule().setCompleted(0);
            myCapsulesInProgressViewModel.getCapsule().setTotalComments(0);
            myCapsulesInProgressViewModel.getCapsule().setLinkComments("");
            myCapsulesInProgressViewModel.getCapsule().setLinkCommentAdd("");
            myCapsulesInProgressViewModel.getCapsule().setViewSlides(0);
            myCapsulesInProgressViewModel.getCapsule().setTotalSlides(0);
            myCapsulesInProgressViewModel.getCapsule().setProgress(0);
            myCapsulesInProgressViewModel.getCapsule().setAddedOn("");
            myCapsulesInProgressViewModel.getCapsule().setUpdatedOn("");


        } else {
            myCapsulesInProgressViewModel.getCapsule().setUuid(capsule.getUuid());
            myCapsulesInProgressViewModel.getCapsule().setTopicUuid(capsule.getTopicUuid());
            myCapsulesInProgressViewModel.getCapsule().setName(capsule.getName());
            myCapsulesInProgressViewModel.getCapsule().setDescription(capsule.getDescription());
            myCapsulesInProgressViewModel.getCapsule().setPosition(capsule.getPosition());
            myCapsulesInProgressViewModel.getCapsule().setImage(capsule.getImage());
            myCapsulesInProgressViewModel.getCapsule().setCompleted(capsule.getCompleted());
            myCapsulesInProgressViewModel.getCapsule().setTotalComments(capsule.getTotalComments());
            myCapsulesInProgressViewModel.getCapsule().setLinkComments(capsule.getLinkComments());
            myCapsulesInProgressViewModel.getCapsule().setLinkCommentAdd(capsule.getLinkCommentAdd());
            myCapsulesInProgressViewModel.getCapsule().setViewSlides(capsule.getViewSlides());
            myCapsulesInProgressViewModel.getCapsule().setTotalSlides(capsule.getTotalSlides());
            myCapsulesInProgressViewModel.getCapsule().setProgress(capsule.getProgress());
            myCapsulesInProgressViewModel.getCapsule().setAddedOn(capsule.getAddedOn());
            myCapsulesInProgressViewModel.getCapsule().setUpdatedOn(capsule.getUpdatedOn());

            ProgressDao progressDao = iTwoGetSkills.getDatabase().getProgressDao();
            Progress progress = progressDao.selectByCapsuleUuid(capsule.getUuid());

            if (progress != null) {
                capsule.setViewSlides(progress.getViewSlides());
                capsule.setTotalSlides(progress.getTotalSlides());
                capsule.setProgress(progress.getProgress());


                myCapsulesInProgressViewModel.getCapsule().setViewSlides(progress.getViewSlides());
                myCapsulesInProgressViewModel.getCapsule().setTotalSlides(progress.getTotalSlides());
                myCapsulesInProgressViewModel.getCapsule().setProgress(progress.getProgress());
            }
        }

        myCapsulesInProgressViewModel.getCapsuleMutableLiveData().setValue(capsule);




    }



    private void loadData(int tabPosition, String search)
    {

        Capsule capsule;
        List<Capsule> dbCapsules;
        CapsuleDao capsuleDao = iTwoGetSkills.getDatabase().getCapsuleDao();

        SlideDao slideDao = iTwoGetSkills.getDatabase().getSlideDao();
        ProgressDao progressDao = iTwoGetSkills.getDatabase().getProgressDao();
        Progress progress;
        switch (tabPosition)
        {
            case Constants.MY_CAPSULES_TAB_IN_PROGRESS :
                if (StringUtils.isEmpty(search)) {
                    dbCapsules = capsuleDao.selectAllInProgress(iTwoGetSkills.getPreference().getUserUuid());
                } else {
                    dbCapsules = capsuleDao.selectAllInProgressWithSearch(iTwoGetSkills.getPreference().getUserUuid(), '%' + search + '%');
                }
               break;

            case Constants.MY_CAPSULES_TAB_COMPLETED:
                if (StringUtils.isEmpty(search)) {
                    dbCapsules = capsuleDao.selectAllCompleted(iTwoGetSkills.getPreference().getUserUuid());
                } else {
                    dbCapsules = capsuleDao.selectAllCompletedWithSearch(iTwoGetSkills.getPreference().getUserUuid(), '%' + search + '%');
                }
                break;

            default :
                if (StringUtils.isEmpty(search)) {
                    dbCapsules = capsuleDao.selectAllPending(iTwoGetSkills.getPreference().getUserUuid());
                } else {
                    dbCapsules = capsuleDao.selectAllPendingWithSearch(iTwoGetSkills.getPreference().getUserUuid(), '%' + search + '%');
                }
                break;

        }
        myCapsulesViewModel.getCapsuleArrayList().clear();
        for (Capsule dbCapsule: dbCapsules) {
            capsule = new Capsule();
            capsule.setUuid(dbCapsule.getUuid());
            capsule.setTopicUuid(dbCapsule.getTopicUuid());
            capsule.setName(dbCapsule.getName());
            capsule.setDescription(dbCapsule.getDescription());
            capsule.setImage(dbCapsule.getImage());
            capsule.setPosition(dbCapsule.getPosition());
            capsule.setLinkCommentAdd(dbCapsule.getLinkCommentAdd());
            capsule.setLinkComments(dbCapsule.getLinkComments());
            capsule.setTotalComments(dbCapsule.getTotalComments());
            capsule.setTotalRating(dbCapsule.getTotalRating());
            capsule.setTotalSlides(0);
            capsule.setViewSlides(0);
            capsule.setProgress(0);
            capsule.setAddedOn(dbCapsule.getAddedOn());
            capsule.setUpdatedOn(dbCapsule.getUpdatedOn());


            progress = progressDao.selectByCapsuleUuid(capsule.getUuid());
            if (progress == null) {
                capsule.setTotalSlides(slideDao.getCountByCapsuleUuid(capsule.getUuid()).getCount());
            } else {
                capsule.setProgress(progress.getProgress());
                capsule.setViewSlides(progress.getViewSlides());
                capsule.setTotalSlides(progress.getTotalSlides());
            }

            myCapsulesViewModel.getCapsuleArrayList().add(capsule);
        }

        myCapsulesViewModel.getCapsuleMutableLiveData().setValue(myCapsulesViewModel.getCapsuleArrayList());

        textViewListingEmpty.setVisibility(dbCapsules.size() == 0 ?  View.VISIBLE : View.GONE);
   }


    @Override
    public void onItemClick(int position, View v) {

        iTwoGetSkills.hideKeyboard(v);

        Capsule capsule = myCapsulesViewModel.getCapsuleArrayList().get(position);
        iTwoGetSkills.changeCapsuleActiveSourceNavigationMyCapsules(capsule.getTopicUuid(), capsule.getUuid());
    }
}