package ai.pai.lensman.session;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.common.utils.DeviceUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import java.io.File;
import java.util.ArrayList;

import ai.pai.lensman.R;
import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.utils.Constants;
import ai.pai.lensman.utils.ImageLoaderUtils;
import butterknife.BindView;
import butterknife.ButterKnife;

public class PhotoRecyclerAdapter extends RecyclerView.Adapter<PhotoRecyclerAdapter.MyViewHolder> {

    private LayoutInflater mInflater;
    private ArrayList<PhotoBean> photoList;
    private int width;
    private  DisplayImageOptions options;

    public PhotoRecyclerAdapter(Context context){
        width = DeviceUtils.getScreenWidth(context);
        mInflater = LayoutInflater.from(context);
        options = ImageLoaderUtils.getOptions(R.drawable.default_img);
    }

    public synchronized void addPhotoBean(PhotoBean item){
        if(photoList==null){
            photoList = new ArrayList<>();
        }
        if(!photoList.contains(item)){
            photoList.add(0,item);
            notifyItemInserted(0);
        }
    }

    public synchronized void removePhotoAtIndex(int index){
        if(photoList==null || photoList.size()<=index){
            return;
        }
        photoList.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return  new MyViewHolder(mInflater.inflate(R.layout.photo_item,parent,false));
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        if(photoList==null){
            return;
        }
        final PhotoBean item = photoList.get(position);
        String path =  Constants.APP_IMAGE_DIR + File.separator+item.sessionId+File.separator+Constants.THUMBNAIL_DIR_NAME+File.separator+item.photoName;
        ImageLoaderUtils.displayLocalImage(path, holder.photo, options);
        int height = width*10/16;
        ViewGroup.LayoutParams lp=holder.photo.getLayoutParams();
        lp.width = width;
        lp.height = height;
        holder.photo.setLayoutParams(lp);
    }

    @Override
    public int getItemCount() {
        if(photoList==null){
            return 0;
        }
        return photoList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        @BindView(R.id.iv_session_photo_item) ImageView photo;

        public MyViewHolder(View view){
            super(view);
            ButterKnife.bind(this,view);
        }
    }
}

