package com.secspace.lib.common.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.secspace.lib.common.R;
import com.secspace.lib.common.adapter.Adapter;

import java.util.List;

/**
 * Created by lichuanzhi@tiankuan.net on 2019/3/15
 */
public class ListDialog extends Dialog {

    private ListAdapter mAdapter;
    private TextView mTvTitle;
    private String mTitle;

    public ListDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        mAdapter = new ListAdapter();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCanceledOnTouchOutside(true);
        setCancelable(true);
        setContentView(R.layout.dialog_list);
        RecyclerView rw = findViewById(R.id.rw_options);
        rw.setAdapter(mAdapter);
        mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText(mTitle);
        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams p = window.getAttributes();
            p.width = (int) (getContext().getResources().getDisplayMetrics().widthPixels * 0.6f);
            window.setAttributes(p);
        }
    }

    public void setTitle(String title) {
        mTitle = title;
        if (mTvTitle != null) {
            mTvTitle.setText(title);
        }
    }

    public void updateAdapter(List<String> options) {
        mAdapter.update(options);
    }

    public void setOnItemClickListener(Adapter.OnItemClickListener<String> onItemClickListener) {
        mAdapter.setOnItemClickListener(onItemClickListener);
    }

    private class ListAdapter extends Adapter<String, Holder> {

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_option, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            holder.mOptionView.setText(getItem(position));
            holder.itemView.setOnClickListener(new OnItemViewClick(position));
            holder.mLine.setVisibility(position == getItemCount() - 1 ? View.GONE : View.VISIBLE);
        }
    }

    private static class Holder extends RecyclerView.ViewHolder {

        private TextView mOptionView;
        private View mLine;

        Holder(@NonNull View itemView) {
            super(itemView);
            mOptionView = itemView.findViewById(R.id.tv_option);
            mLine = itemView.findViewById(R.id.line);
        }
    }
}
