package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.adapter.LearningPathAdapter;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.LearningPath;
import com.cygnusa.hyperm.wrappers.LearningPathResponse;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import java.util.ArrayList;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LearningPathActivity extends AppCompatActivity {
    View mainView;


    TransparentProgressDialog progressDialog;
    ApiService restService;
    ArrayList<LearningPath> MY_LEARNING_PATH = new ArrayList<>();

    private int SHOWCASE_POSITION = 0;
    EmptyStateRecyclerView learningPath;

    public static Handler.Callback callback;
    LearningPathAdapter adapter;
    LinearLayoutManager linearLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learning_path);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));
        restService = ((MainApplication)getApplication()).getClient();
        learningPath =findViewById(R.id.learningPath);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
        learningPath.post(new Runnable() {
            @Override
            public void run() {
                getLearningPath();
            }
        });
        findViewById(R.id.helpIcon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  showHelpScreen();
            }
        });

    }

    private void getLearningPath() {

        if (new UtilService().isNetworkAvailable(this)) {
            progressDialog = new TransparentProgressDialog(this);
            progressDialog.show();

            try {
                restService.getLearningPath()
                        .enqueue(new Callback<LearningPathResponse>() {
                            @Override
                            public void onResponse(Call<LearningPathResponse> call, Response<LearningPathResponse> response) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }

                                if (response.body() != null && response.body().getStatus() == 200) {
                                    MY_LEARNING_PATH = response.body().getData();


                                    if (MY_LEARNING_PATH == null) {
                                        MY_LEARNING_PATH = new ArrayList<>();
                                    }

                                    if (MY_LEARNING_PATH.size() == 0) {
                                        learningPath.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                                    } else {
                                        learningPath.invokeState(EmptyStateRecyclerView.STATE_OK);
                                    }
                                    setLearningPath();
                                } else if (response.body() != null && response.body().getStatus() == 401) {
                                    GlobalData.canLogout = true;
                                    new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                } else if (response.body() != null) {
                                    GlobalData.showToast(LearningPathActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                                } else if (response.errorBody() != null) {
                                    Gson gson = new Gson();
                                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                    GlobalData.showToast(LearningPathActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                                    if (message.getStatus() == 401) {
                                        GlobalData.canLogout = true;
                                        new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<LearningPathResponse> call, Throwable t) {
                                if (progressDialog != null && progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                GlobalData.showToast(LearningPathActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                            }
                        });

            } catch (Exception e) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                GlobalData.showToast(this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
            }
        } else {
            GlobalData.showToast(this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    public void setLearningPath() {
        learningPath.setHasFixedSize(true);
        learningPath.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        learningPath.setLayoutManager(linearLayoutManager);
        learningPath.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(this, "No data available", ""));

        adapter = new LearningPathAdapter(this,  MY_LEARNING_PATH);

        learningPath.setAdapter(adapter);

    }


    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(LearningPathActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        if (GlobalData.canLogout) {
            finish();
        }
    }

    private void showHelpScreen() {
        try {
            View view;
            if (adapter != null && adapter.getItemCount() > 0) {
                view = learningPath.findViewHolderForAdapterPosition(linearLayoutManager.findFirstVisibleItemPosition()).itemView;
            } else {
                view = learningPath;
            }
            new FancyShowCaseView.Builder(this)
                    .focusOn(view)
                    .title("Tap here to view the PDF or Video")
                    .titleSize(22, 1)
                    .closeOnTouch(true)
                    .fitSystemWindows(false)
                    .focusShape(FocusShape.ROUNDED_RECTANGLE)
                    .backgroundColor(Color.parseColor("#99000000"))
                    .build()
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            confirmClose();
        }
        return super.onOptionsItemSelected(item);
    }

    private void confirmClose() {
        finish();
        LearningPathActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }


}
