package ch.pizzalemon.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
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 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 19/09/2017.
 */

public class ProductFragment extends BaseFragment {

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

    public static final String FRAGMENT_NAME = "productFragment";
    private int REQUEST_CODE_PRODUCT_PROPERTIES = 3768;

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

    public ProductFragment() {}

    public static ProductFragment newInstance(CategoryModel categoryModel) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("categoryModel", categoryModel);
        ProductFragment fragment = new ProductFragment();
        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_product, container, false);
        ButterKnife.bind(this, view);
        getDataFromArguments();
        initViews();
        getProductById();
        return view;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        FragmentActivity fragmentActivity = getActivity();
        if(requestCode == REQUEST_CODE_PRODUCT_PROPERTIES &&
                resultCode == RESULT_OK &&
                fragmentActivity instanceof MainActivity){
            MainActivity mainActivity = (MainActivity) fragmentActivity;
            BaseActivity.setCurrentActivity(mainActivity);
            BaseActivity.setCurrentActivity((MainActivity) fragmentActivity);
            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);
        customProductRecyclerView.setLayoutManager(layoutManager);
        menuProductRecyclerAdapter = new MenuProductRecyclerAdapter(
                productList,
                categoryModel.isDescriptionVisible(),
                new RecyclerItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Intent productPropertiesIntent = new Intent(BaseActivity.currentActivity, ProductDetailsActivity.class);
                        productPropertiesIntent.putExtra("menuProductModel", productList.get(position));
                        startActivityForResult(productPropertiesIntent, REQUEST_CODE_PRODUCT_PROPERTIES);
                    }
                });
        customProductRecyclerView.addItemDecoration(new GridSpacesItemDecoration(2, 16, true));
        customProductRecyclerView.setAdapter(menuProductRecyclerAdapter);
    }

    private void getProductById(){
        DialogHelper.showLoadingDialog();
        Call<ResponseArray<MenuProductModel>> call = ApiService.apiInterface.getProductById(
                SessionHelper.getSelectedStore().getStoreName(),
                getProductIdByCategory());
        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())
                    setProductFields(response.body().getData());
                else
                    ApiErrorUtils.parseError(response);
            }

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

    private void setProductFields(ArrayList<MenuProductModel> prdctLst){
        if(prdctLst == null || prdctLst.size() == 0)
            return;
        MenuProductModel.checkNull(prdctLst);
        productList.clear();
        productList.addAll(prdctLst);
        menuProductRecyclerAdapter.notifyDataSetChanged();

    }

    private int getProductIdByCategory(){
        String productIdString = "";
        if(categoryModel.isSpecialCategory()){
            productIdString = categoryModel.getSpecialProductId();
        }
        int productIdInt;
        try{
            productIdInt = Integer.valueOf(productIdString);
        }catch (Exception e){
            productIdInt = 0;
        }
        return productIdInt;
    }

    private void sortProductsByName(){

    }
}