package com.app.simplitend.articles;

import static com.app.simplitend.articles.ArticleShowerActivity.ARTICLE_TITLE;
import static com.app.simplitend.articles.ArticleShowerActivity.ARTICLE_URL_KEY;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.databinding.ActivityArticlesBinding;

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

public class ArticlesActivity extends AppCompatActivity
        implements ArticlesAdapter.ArticleClickListener, ArticleContracts.GetArticleCallback {

    private static final int PER_PAGE_COUNT = 10;
    protected ActivityArticlesBinding binding;

    private ArticlePresenter presenter;

    private ArticlesAdapter articlesAdapter;
    
    private boolean isLoadingArticles, lastPageHit, areSearchedArticleShown;

    private int page_no;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityArticlesBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        presenter = ArticlePresenter.getArticlePresenter();

        initViews();

        clickEvents();

        page_no = 1;
        areSearchedArticleShown = false;
        getArticles(binding.searchEt.getText().toString().trim(), PER_PAGE_COUNT, page_no, false);

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    private void getArticles(String search_query, int per_page, int page_no, boolean bottom_progress) {

        binding.noArticles.setVisibility(View.GONE);

        if (bottom_progress){
            binding.pageProgress.setVisibility(View.VISIBLE);
            binding.searchView.setVisibility(View.GONE);
        }else{
            binding.progressBar.setVisibility(View.VISIBLE);
            articlesAdapter.submitList(null);
        }

        isLoadingArticles = true;
        presenter.getArticles("Bearer " + AppUtil.getCgToken(this), search_query, per_page, page_no,this);
    }

    private void initViews() {
        binding.articlesRv.setLayoutManager(new LinearLayoutManager(this));
        articlesAdapter = new ArticlesAdapter(this);
        binding.articlesRv.setAdapter(articlesAdapter);

        // pagination
        binding.articlesRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                if (!isLoadingArticles && !lastPageHit) {
                    if ((visibleItemCount + firstVisibleItemPosition) >= (totalItemCount)
                            && firstVisibleItemPosition >= 0) {
                        getArticles(binding.searchEt.getText().toString(), 10, ++page_no, true);
                    }
                }
            }
        });

        binding.searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 0 && areSearchedArticleShown){
                    // loading all articles
                    page_no = 1;
                    areSearchedArticleShown = false;
                    getArticles(binding.searchEt.getText().toString().trim(), PER_PAGE_COUNT, page_no, false);
                }
            }
        });
    }

    private void clickEvents() {
        binding.backBtn.setOnClickListener(v -> {
            onBackPressed();
        });

        binding.closeBtn.setOnClickListener(v -> {
            if (!binding.searchEt.getText().toString().trim().isEmpty() && areSearchedArticleShown){
                page_no = 1;
                areSearchedArticleShown = false;
                getArticles("", PER_PAGE_COUNT, page_no, false);
            }

            binding.searchEt.setText("");
            AppUtil.closeKeyboard(this);
        });

        binding.searchEt.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (binding.searchEt.getText().toString().trim().isEmpty()){
                return true;
            }

            AppUtil.closeKeyboard(this);
            page_no = 1;
            areSearchedArticleShown = true;
            getArticles(binding.searchEt.getText().toString().trim(), PER_PAGE_COUNT, page_no, false);
            return true;
        });
    }

    @Override
    public void onArticleClick(ArticleResult articleResult) {
        Intent intent = new Intent(this, ArticleShowerActivity.class);
        intent.putExtra(ARTICLE_URL_KEY, articleResult.article_link);
        intent.putExtra(ARTICLE_TITLE, articleResult.article_title);
        startActivity(intent);
    }

    @Override
    public void onArticlesFetched(ArrayList<ArticleResult> articleResults) {
        isLoadingArticles = false;
        lastPageHit = articleResults.size() < PER_PAGE_COUNT; // there are no articles left at server side to be fetched.

        binding.progressBar.setVisibility(View.GONE);
        binding.pageProgress.setVisibility(View.GONE);
        binding.noArticles.setVisibility(View.GONE);
        binding.searchView.setVisibility(View.VISIBLE);

        List<ArticleResult> currentArticleList = articlesAdapter.getCurrentList();

        ArrayList<ArticleResult> totalArticles = new ArrayList<>(currentArticleList);
        totalArticles.addAll(articleResults);

        if (totalArticles.isEmpty()){
            binding.noArticles.setVisibility(View.VISIBLE);
        }

        articlesAdapter.submitList(totalArticles);
    }

    @Override
    public void onArticleFetchFailed(Throwable t, String message) {
        binding.progressBar.setVisibility(View.GONE);
        binding.pageProgress.setVisibility(View.GONE);
        binding.noArticles.setVisibility(View.VISIBLE);
        binding.searchView.setVisibility(View.GONE);

        Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
    }
}