package com.dowerx.quack.fragment;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;

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.User;
import com.dowerx.quack.service.UserService;

import java.util.List;

public class SearchFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<User>> {

    private Dialog progress;

    private RecyclerView recyclerView;
    private EditText query;

    public SearchFragment() {
    }


    public static SearchFragment newInstance() {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

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

        if (getArguments() != null) {
        }
    }

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

        Context context = view.getContext();
        recyclerView = view.findViewById(R.id.list);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));

        query = view.findViewById(R.id.query);
        LoaderManager.getInstance(this).initLoader(1, null, this);
        view.findViewById(R.id.search).setOnClickListener(v -> {
            LoaderManager.getInstance(this).destroyLoader(1);
            LoaderManager.getInstance(this).initLoader(1, null, this);
        });

        return view;
    }

    @NonNull
    @Override
    public Loader<List<User>> onCreateLoader(int id, @Nullable Bundle args) {
        progress = new Dialog(getContext());
        progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
        progress.setContentView(R.layout.loading);
        progress.show();
        return new UserService.SearchUsername(query.getText().toString(), getContext());
    }

    @Override
    public void onLoadFinished(@NonNull Loader<List<User>> loader, List<User> data) {
        progress.cancel();
        recyclerView.setAdapter(new UserRecyclerViewAdapter(data, (SwitcherActivity) getContext()));
    }

    @Override
    public void onLoaderReset(@NonNull Loader<List<User>> loader) {

    }
}