package com.dowerx.quack.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

import com.dowerx.quack.R;
import com.dowerx.quack.model.User;
import com.dowerx.quack.service.AuthService;
import com.dowerx.quack.service.UserService;


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

    private Dialog progress;

    private static final String ID = "id";

    private String id;
    private View view;

    public ProfileFragment() {
        // Required empty public constructor
    }

    public static ProfileFragment newInstance(String id) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ID, id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null && !getArguments().getString(ID).isEmpty()) {
            id = getArguments().getString(ID);
        } else {
            id = AuthService.getId();
        }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_profile, container, false);
        return view;
    }

    @NonNull
    @Override
    public Loader<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.GetUserById(getContext(), this.id);
    }

    @Override
    public void onLoadFinished(@NonNull Loader<User> loader, User data) {
        progress.cancel();
        ((TextView)view.findViewById(R.id.profile_username)).setText(data.getUsername());
        getParentFragmentManager()
                .beginTransaction()
                .replace(R.id.profile_posts_holder, ProfileFeedFragment.newInstance(data.getUsername()))
                .commit();
    }

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

    }
}