package com.geek.demo.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.geek.demo.R;
import com.geek.demo.model.ServiceData;
import com.geek.demo.utils.MyUtils;

import java.util.ArrayList;
import java.util.List;

public class SceneServiceAdapter extends RecyclerView.Adapter<SceneServiceAdapter.RecyclerHolder> {

    private Context context;
    private List<ServiceData> dataList = new ArrayList<>();

    public SceneServiceAdapter(RecyclerView recyclerView) {
        this.context = recyclerView.getContext();
    }

    public void setData(List<ServiceData> dataList) {
        if (null != dataList) {
            this.dataList.clear();
            this.dataList.addAll(dataList);
            notifyDataSetChanged();
        }
    }

    @Override
    public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_service, parent, false);
        return new RecyclerHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerHolder holder, final int position) {
        ServiceData sceneService = dataList.get(position);

        String serviceName = sceneService.serviceName;
        String iconFileUrl = sceneService.iconFileUrl;
        String iconHttpUrl = sceneService.iconHttpUrl;

        holder.tvServiceName.setText(serviceName);
        String serviceIconUrl = iconFileUrl;
        if (TextUtils.isEmpty(iconFileUrl)) {
            serviceIconUrl = iconHttpUrl;
        }
        holder.llService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyUtils.openUrl(context, dataList.get(position).actionUrl);
            }
        });
        if (TextUtils.isEmpty(serviceIconUrl)) {
            holder.ivLogo.setImageResource(R.drawable.service_default_logo);
        } else {
            MyUtils.loadImage(TextUtils.isEmpty(serviceIconUrl) ? "file:///android_asset/icon_service_default_logo.png" : serviceIconUrl, holder.ivLogo, context);
        }
    }

    @Override
    public int getItemCount() {
        Log.i("=====", "测试个数 ： " + dataList.size());
        return dataList.size();
    }

    class RecyclerHolder extends RecyclerView.ViewHolder {
        TextView tvServiceName;
        ImageView ivLogo;
        LinearLayout llService;

        private RecyclerHolder(View itemView) {
            super(itemView);
            llService = itemView.findViewById(R.id.ll_service);
            ivLogo = itemView.findViewById(R.id.iv_service_logo);
            tvServiceName = itemView.findViewById(R.id.tv_service_name);
        }
    }
}
