package org.keyscience.fragments;

import android.content.Intent;
import android.graphics.Point;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import org.keyscience.BackgroundTask.LoadContentTask;
import org.keyscience.R;
import org.keyscience.SingletonPattern.ListSingleton;
import org.keyscience.adapters.EventsAdapter;
import org.keyscience.models.EventsNewsModel;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;

public class DynamicContentFragment extends Fragment {

    private RecyclerView recyclerView;
    private LoadContentTask task;
    private LinearLayout linearLayout;
    private ListSingleton<EventsNewsModel> data;
    private Button readMoreButton;
    private ImageView header;
    private int listType;

    private String jsonUrl;
    private String phpUrl;
    private String readMoreLink;

    @Override
    public void setArguments(@Nullable Bundle args) {
        super.setArguments(args);
        jsonUrl = args.getString("json");
        phpUrl = args.getString("php");
        readMoreLink = args.getString("readMoreLink");
        listType = args.getInt("listType");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.events_fragment, container, false);
        readMoreButton = view.findViewById(R.id.readMoreDynamic);
        readMoreButton.setVisibility(View.GONE);
        readMoreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(readMoreLink));
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    startActivity(intent);
                }
            }
        });

        header = view.findViewById(R.id.headerImageDynamic);
        // set header image based on content type
        if (listType == 0) {
            header.setImageResource(R.drawable.events_header);
        } else {
            header.setImageResource(R.drawable.news_header);
        }

        linearLayout = view.findViewById(R.id.load_animation_linearLayout);

        Display display = (getActivity().getWindowManager().getDefaultDisplay());
        Point size = new Point();
        display.getSize(size);
        int height = size.y;
        linearLayout.setMinimumHeight(height - 180);


        setUpRecyclerView(view);
        return view;
    }

    private void setUpRecyclerView(View view) {
        recyclerView = view.findViewById(R.id.events_recyclerView);
        recyclerView.setFocusable(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // recyclerview content is fetched from the URL by an Async task.
        // When done, async task will set the recycler adapter

        data = ListSingleton.getListInstance(listType);

        // if data has been already fetched, we are not going to download again. the list already has
        // data.
        if (data.size() == 0) {
            task = new LoadContentTask(recyclerView, getContext(), data, linearLayout, readMoreButton);
            task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, phpUrl, jsonUrl);
        } else {
            readMoreButton.setVisibility(View.VISIBLE);
            linearLayout.setVisibility(View.GONE);
            EventsAdapter adapter = new EventsAdapter(data.getList(), getContext());
            recyclerView.setAdapter(adapter);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (task != null) {
            task.cancel(true);
            try {
                //Waits if necessary to complete
                task.get();
            } catch (ExecutionException e) {
                //  ignore
            } catch (InterruptedException e) {
                //  ignore
            } catch (CancellationException e) {
                //  ignore
            }
            task = null;
        }
    }

}
