package ch.pizzalemon.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import butterknife.BindView;
import butterknife.ButterKnife;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.activity.BaseActivity;
import ch.pizzalemon.android.activity.MainActivity;
import ch.pizzalemon.android.activity.ProductDetailsActivity;
import ch.pizzalemon.android.adapter.recycler.MenuProductRecyclerAdapter;
import ch.pizzalemon.android.api.ApiErrorUtils;
import ch.pizzalemon.android.api.ApiService;
import ch.pizzalemon.android.api.ResponseArray;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.interfaces.RecyclerItemClickListener;
import ch.pizzalemon.android.model.CategoryModel;
import ch.pizzalemon.android.model.menu.MenuProductModel;
import ch.pizzalemon.android.view.GridSpacesItemDecoration;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * Created by cimenmus on 02/10/2017.
 */

public class MenuFragment extends BaseFragment {

    @BindView(R.id.menuProductRecyclerView) RecyclerView menuProductRecyclerView;

    public static final String FRAGMENT_NAME = "menuFragment";
    private int REQUEST_CODE_PRODUCT_PROPERTIES = 3765;

    private ArrayList<MenuProductModel> menuProductList = new ArrayList<>();
    private MenuProductRecyclerAdapter menuProductRecyclerAdapter;
    private CategoryModel categoryModel;

    public MenuFragment() {}

    public static MenuFragment newInstance(CategoryModel categoryModel) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("categoryModel", categoryModel);
        MenuFragment fragment = new MenuFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_menu, container, false);
        ButterKnife.bind(this, view);
        getDataFromArguments();
        initViews();
        getProductsByCategory();
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_PRODUCT_PROPERTIES &&
                resultCode == RESULT_OK &&
                getActivity() != null &&
                getActivity() instanceof MainActivity){
            BaseActivity.currentActivity = (MainActivity)getActivity();
            MainActivity mainActivity = (MainActivity) BaseActivity.currentActivity;
            mainActivity.setCartItemCount();
        }
    }

    private void getDataFromArguments(){
        categoryModel = (CategoryModel) getArguments().getSerializable("categoryModel");
    }

    private void initViews(){
        setPizzalinkToolbarFields(true, categoryModel.getName());
        initRecyclerView();
    }

    private void initRecyclerView(){
        GridLayoutManager layoutManager = new GridLayoutManager(BaseActivity.currentActivity, 2);
        menuProductRecyclerView.setLayoutManager(layoutManager);
        menuProductRecyclerAdapter = new MenuProductRecyclerAdapter(
                menuProductList,
                categoryModel.isDescriptionVisible(),
                new RecyclerItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Intent productPropertiesIntent = new Intent(BaseActivity.currentActivity, ProductDetailsActivity.class);
                        productPropertiesIntent.putExtra("menuProductModel", menuProductList.get(position));
                        startActivityForResult(productPropertiesIntent, REQUEST_CODE_PRODUCT_PROPERTIES);
                    }
                });
        menuProductRecyclerView.addItemDecoration(new GridSpacesItemDecoration(2, 16, true));
        menuProductRecyclerView.setAdapter(menuProductRecyclerAdapter);
    }

    private void getProductsByCategory(){
        DialogHelper.showLoadingDialog();
        Call<ResponseArray<MenuProductModel>> call = ApiService.apiInterface.getProductsByCategory(
                SessionHelper.getSelectedStore().getStoreName(),
                categoryModel.getCategoryIdString());
        call.enqueue(new Callback<ResponseArray<MenuProductModel>>() {
            @Override
            public void onResponse(Call<ResponseArray<MenuProductModel>> call, Response<ResponseArray<MenuProductModel>> response) {
                DialogHelper.hideLoadingDialog();
                if(response.isSuccessful() &&
                        response.body().getData() != null &&
                        response.body().isSuccess())
                    fillAndNotifyProductList(response.body().getData());
                else
                    ApiErrorUtils.parseError(response);
            }

            @Override
            public void onFailure(Call<ResponseArray<MenuProductModel>> call, Throwable t) {
                DialogHelper.hideLoadingDialog();
                DialogHelper.showFailedDialog();
            }
        });
    }

    private void fillAndNotifyProductList(ArrayList<MenuProductModel> productList){
        MenuProductModel.checkNull(productList);
        menuProductList.clear();
        menuProductList.addAll(productList);
        sortProductsByName();
        menuProductRecyclerAdapter.notifyDataSetChanged();
    }

    private void sortProductsByName(){
        Collections.sort(menuProductList, new Comparator<MenuProductModel>() {
            @Override
            public int compare(MenuProductModel product1, MenuProductModel product2) {
                return  product1.getName().compareTo(product2.getName());
            }
        });
    }

}
