package com.handset.serialportsensor.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
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.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handset.serialportsensor.R;
import com.handset.serialportsensor.bean.Sensor;
import com.handset.serialportsensor.bean.TestRecordsTotal;
import com.handset.serialportsensor.constant.Constant;
import com.handset.serialportsensor.utils.Utils;
import com.handset.serialportsensor.view.LinearLayoutManagerCus;

import org.kymjs.kjframe.KJDB;

import java.util.List;

public class HistoryActivity extends AppCompatActivity {
    private static final String logTag = "HANDSET-JE002-EX";
    private boolean delStatus = false;
    private RecyclerView mRecyclerView;
    private MyAdapter myAdapter;
    private LinearLayout llDeleteContent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        mRecyclerView = findViewById(R.id.recycle_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManagerCus(this));
        DefaultItemAnimator animator = new DefaultItemAnimator();
        animator.setRemoveDuration(1000);
        mRecyclerView.setItemAnimator(animator);
        initData();
        TextView tvTitle = findViewById(R.id.title_text);
        ImageView ivBack = findViewById(R.id.title_back);
        tvTitle.setText(R.string.test_history);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener((View v) -> HistoryActivity.this.finish());

        Button btnSelAll = findViewById(R.id.btn_select_all);
        btnSelAll.setOnClickListener((View v) -> myAdapter.selAll());
        Button btnDelete = findViewById(R.id.btn_delete);
        btnDelete.setOnClickListener((View v) -> {
            delStatus = false;
            llDeleteContent.setVisibility(View.GONE);
            myAdapter.delSelected();
        });
        Button btnCancel = findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener((View v) -> {
            llDeleteContent.setVisibility(View.GONE);
            myAdapter.setDeleteStatus(false);
            delStatus = false;
            myAdapter.cancelSelected();
        });

        llDeleteContent = findViewById(R.id.ll_delete_content);
        llDeleteContent.setVisibility(View.GONE);
        //initSensor();
    }

    void initData() {
        final List<Sensor> sensors = KJDB.getDefaultInstance().findAll(Sensor.class);
        for (Sensor sensor : sensors) {
            Log.i(logTag, ("list every sensorId: " + sensor.sensor_id + ", id: " + sensor.id));
        }
        if (myAdapter == null) {
            myAdapter = new MyAdapter(sensors, (View v) -> {
                if (delStatus) {
                    return true;
                } else {
                    delStatus = true;
                    myAdapter.setDeleteStatus(true);
                    llDeleteContent.setVisibility(View.VISIBLE);
                }
                return false;

            });
        }
        myAdapter.setOnItemClickListener((View view, int position) -> {
            Intent intent = new Intent((HistoryActivity.this), HistoryDetailActivity.class);
            Log.e(logTag, "History Activity id: " + sensors.get(position).id + ", sensorId: " + sensors.get(position).sensor_id);
            intent.putExtra(Constant.SENSOR_ID, sensors.get(position).id);
            startActivity(intent);

        });
        mRecyclerView.setAdapter(myAdapter);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvEggNum;
        private TextView tvEggType;
        private TextView tvConeNo;
        private TextView tvSensorId;
        private TextView tvConeUsedTimes;
        private TextView tvPro;
        private LinearLayout llItem;
        private ImageView ivSelectStatus;

        private ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvEggNum = itemView.findViewById(R.id.tv_his_egg_num);
            tvEggType = itemView.findViewById(R.id.tv_his_egg_type);
            tvConeNo = itemView.findViewById(R.id.tv_his_cone_no);
            tvSensorId = itemView.findViewById(R.id.tv_his_sensor_id);
            tvPro = itemView.findViewById(R.id.tv_his_pro);
            tvConeUsedTimes = itemView.findViewById(R.id.tv_his_cone_used_times);
            llItem = itemView.findViewById(R.id.ll_his_item);
            ivSelectStatus = itemView.findViewById(R.id.iv_select_status);
        }
    }

    public static class MyAdapter extends RecyclerView.Adapter<ViewHolder> {
        private boolean delStatus = false;
        private List<Sensor> mDataList;
        private OnItemClickListener mOnItemClickListener;
        private View.OnLongClickListener mOnLongClickListener;

        MyAdapter(List<Sensor> mList, View.OnLongClickListener longClickListener) {
            this.mDataList = mList;
            this.mOnLongClickListener = longClickListener;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.history_item, viewGroup, (false)));
        }

        @Override
        public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
            final Sensor sensor = mDataList.get(i);
            viewHolder.tvEggNum.setText(TextUtils.isEmpty(sensor.egg_id) ? " " : " ".concat(sensor.egg_id));
            viewHolder.tvEggType.setText(TextUtils.isEmpty(sensor.egg_type) ? " " : " ".concat(sensor.egg_type));
            viewHolder.tvConeNo.setText(TextUtils.isEmpty(sensor.tupe_id) ? " " : " ".concat(sensor.tupe_id));
            viewHolder.tvSensorId.setText(Utils.getSensorNoShow(String.valueOf(sensor.sensor_id)));
            viewHolder.tvPro.setText(String.valueOf(sensor.sensor_id).length() < 5 ? "" : String.valueOf(String.valueOf(sensor.sensor_id).charAt(4)));
            viewHolder.llItem.setOnLongClickListener((View v) -> {
                if (mOnLongClickListener != null) {
                    mOnLongClickListener.onLongClick(v);
                }
                return false;

            });
            viewHolder.ivSelectStatus.setVisibility(this.delStatus ? View.VISIBLE : View.GONE);
            if (delStatus) {
                viewHolder.ivSelectStatus.setImageResource(sensor.tagBackup == 1 ? R.mipmap.ic_selected : R.mipmap.ic_default);
                viewHolder.llItem.setOnClickListener((View v) -> {
                    sensor.tagBackup = sensor.tagBackup == 0 ? 1 : 0;
                    notifyDataSetChanged();
                });
            } else {
                viewHolder.llItem.setOnClickListener((View v) -> {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(v, viewHolder.getAdapterPosition());
                    }
                });
            }
            viewHolder.tvConeUsedTimes.setText(" ".concat(TextUtils.isEmpty(sensor.tv_tupe_use_times) ? "0" : sensor.tv_tupe_use_times));
        }

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

        private void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.mOnItemClickListener = onItemClickListener;
        }

        private void setDeleteStatus(boolean delStatus) {
            this.delStatus = delStatus;
            notifyDataSetChanged();
        }

        void selAll() {
            for (Sensor sensor : mDataList) {
                sensor.tagBackup = 1;
            }
            notifyDataSetChanged();
        }

        private void delSelected() {
            for (int i = mDataList.size() - 1; i >= 0; i--) {
                Sensor t = mDataList.get(i);
                if (t.tagBackup == 1) {
                    KJDB.getDefaultInstance().deleteByWhere(TestRecordsTotal.class, "sensor_id = " + t.sensor_id);
                    KJDB.getDefaultInstance().deleteById(Sensor.class, t.id);
                    mDataList.remove(i);
                }
            }
            delStatus = false;
            notifyDataSetChanged();
        }

        private void cancelSelected() {
            for (Sensor sensor : mDataList) {
                sensor.tagBackup = 0;
            }
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    @SuppressWarnings(value = "all")
    void initSensor() {
        Sensor sensor = new Sensor();
        sensor.id = 1;
        sensor.egg_id = "EGG1";
        sensor.sensor_id = 19011111;
        sensor.egg_type = "EGGA";
        sensor.tupe_id = "TUPEA";
        KJDB.getDefaultInstance().save(sensor);
        sensor.id = 2;
        sensor.egg_id = "EGG2";
        sensor.sensor_id = 19011112;
        sensor.egg_type = "EGGB";
        sensor.tupe_id = "TUPEB";
        KJDB.getDefaultInstance().save(sensor);

        TestRecordsTotal testRecordsTotal = new TestRecordsTotal();
        int i = 1;
        for (; i < 25; i++) {

            testRecordsTotal.id = i;
            testRecordsTotal.end_time = System.currentTimeMillis();
            testRecordsTotal.Hum = 80;
            testRecordsTotal.sensor_id = 1;
            testRecordsTotal.pressure_yacha = 100;
            testRecordsTotal.pressurein = 90;
            testRecordsTotal.pressureout = 120;
            testRecordsTotal.temp = 50;
            testRecordsTotal.Hum20 = 90;
            testRecordsTotal.pressurein20 = 20;
            testRecordsTotal.tupe_use_times = "10";
            KJDB.getDefaultInstance().save(testRecordsTotal);
        }
        i = 1;
        for (; i < 25; i++) {
            testRecordsTotal.id = i;
            testRecordsTotal.Hum = 80;
            testRecordsTotal.sensor_id = 1;
            testRecordsTotal.pressure_yacha = 100;
            testRecordsTotal.pressurein = 90;
            testRecordsTotal.pressureout = 120;
            testRecordsTotal.temp = 50;
            testRecordsTotal.Hum20 = 90;
            testRecordsTotal.pressurein20 = 20;
            testRecordsTotal.tupe_use_times = "10";
            KJDB.getDefaultInstance().save(testRecordsTotal);
        }

        i = 1;
        for (; i < 25; i++) {
            testRecordsTotal.id = i;
            testRecordsTotal.end_time = System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000;
            testRecordsTotal.Hum = 80;
            testRecordsTotal.sensor_id = 1;
            testRecordsTotal.pressure_yacha = 100;
            testRecordsTotal.pressurein = 90;
            testRecordsTotal.pressureout = 120;
            testRecordsTotal.temp = 50;
            testRecordsTotal.Hum20 = 90;
            testRecordsTotal.pressurein20 = 20;
            testRecordsTotal.tupe_use_times = "10";
            KJDB.getDefaultInstance().save(testRecordsTotal);
        }
    }
}
