package org.keyscience.adapters;

import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import org.keyscience.R;
import org.keyscience.app.HomeActivity;
import org.keyscience.models.OurPartnersModel;

import java.util.List;

public class OurPartnersAdapter extends RecyclerView.Adapter<OurPartnersAdapter.OurPartnersViewModel> {


    private LayoutInflater inflater;
    private List<OurPartnersModel> mData;
    private Context context;

    public OurPartnersAdapter(List<OurPartnersModel> mData, Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.mData = mData;
    }

    @NonNull
    @Override
    public OurPartnersViewModel onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = inflater.inflate(R.layout.our_partners_item, viewGroup, false);
        return new OurPartnersViewModel(view);
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    @Override
    public void onBindViewHolder(@NonNull OurPartnersViewModel ourPartnersViewModel, int i) {
        ourPartnersViewModel.setData(mData.get(i));
    }

    class OurPartnersViewModel extends RecyclerView.ViewHolder {

        ImageView image;

        public OurPartnersViewModel(@NonNull View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.op_image);
        }

        public void setData(final OurPartnersModel model) {

            image.setImageResource(model.getImageID());

            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(model.getLink()));
                    if (intent.resolveActivity(context.getPackageManager()) != null) {
                        context.startActivity(intent);
                    }
                }
            });

            // resize images to fit screen
            Display display = ((HomeActivity) context).getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int width = size.x;
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width / 2 - 10, width / 2 - 10);
            image.setLayoutParams(layoutParams);
        }
    }
}
