package com.dowerx.quack.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dowerx.quack.R;
import com.dowerx.quack.activity.SwitcherActivity;
import com.dowerx.quack.model.Post;
import com.dowerx.quack.service.PostService;

import java.util.List;

public class ProfileFeedFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Post>> {

    private RecyclerView recyclerView;
    private String username;
    private final static String USERNAME = "username";


    public ProfileFeedFragment() {
    }

    @SuppressWarnings("unused")
    public static ProfileFeedFragment newInstance(String username) {
        ProfileFeedFragment fragment = new ProfileFeedFragment();
        Bundle args = new Bundle();
        args.putString(USERNAME, username);
        fragment.setArguments(args);
        return fragment;
    }

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

        if (getArguments() != null) {
            this.username = getArguments().getString(USERNAME);
        }

        LoaderManager.getInstance(this).initLoader(1, null, this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_feed_list, container, false);

        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            recyclerView = (RecyclerView) view;
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        }
        return view;
    }

    @NonNull
    @Override
    public Loader<List<Post>> onCreateLoader(int id, @Nullable Bundle args) {
        Log.d(this.getClass().getName(), "onCreateLoader");
        return new PostService.GetProfileFeed(getContext(), this.username);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<Post>> loader, List<Post> data) {
        Log.d(this.getClass().getName(), "onLoadFinished");
        Log.d(this.getClass().getName(), data.toString());
        recyclerView.setAdapter(new PostRecyclerViewAdapter(data, (SwitcherActivity)getContext()));
    }

    @Override
    public void onLoaderReset(@NonNull Loader loader) {

    }

}