package com.handset.serialportsensor.activity;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.handset.serialportsensor.R;
import com.handset.serialportsensor.utils.DateUtils;
import com.handset.serialportsensor.utils.Slog;
import com.handset.serialportsensor.utils.ToastHelper;
import com.handset.serialportsensor.utils.ExcelMa;
import com.handset.serialportsensor.utils.PersistHelper;
import com.handset.serialportsensor.view.ExportProgressDialog;
import com.handset.serialportsensor.view.LinearLayoutManagerCus;

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

import static com.handset.serialportsensor.utils.DateStyle.YYYY_MM_DD_HH_MM_SS;

/**
 * Created by zy on 2019/3/11.
 */

public class DataRecoverActivity extends BaseActivity {
    private final String TAG = getClass().getSimpleName();
    private RecyclerView mRecyclerView;
    private MyAdapter myAdapter;

    boolean isRecovering = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recover_data);
        TextView tvTitle = findViewById(R.id.title_text);
        ImageView ivBack = findViewById(R.id.title_back);
        tvTitle.setText(R.string.data_recovery);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener((View v) -> onBackPressed());
        findViewById(R.id.btn_sure).setOnClickListener((View v) -> {
            int index = myAdapter.getSelectIndex();
            if (index != -1) {
                showRecoverConfirm(index);
            }
        });
        mRecyclerView = findViewById(R.id.recycle_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManagerCus((this)));
        DefaultItemAnimator animator = new DefaultItemAnimator();
        animator.setRemoveDuration(1000);
        mRecyclerView.setItemAnimator(animator);
        getLocalFiles();
    }

    ExcelMa excelMa = new ExcelMa();

    boolean recoverStatus = true;

    private void recoverExcel(final int index) {
        if (mFiles != null) {
            mExportProgressDialog = null;
            new Thread(() ->
                    excelMa.onReadClick(mFiles.get(index), new PersistHelper.ExportCallback() {
                        @Override
                        public void exportProgress(int counts, int remain) {
                            updateView(counts, remain);
                            recoverStatus = true;
                        }

                        @Override
                        public void finish(int counts, int remain) {
                            if (remain != 0) {
                                showCancelTip();
                                recoverStatus = true;
                            } else {
                                recoverStatus = false;
                            }
                        }
                    })
            ).start();
        }
    }

    private void showCancelTip() {
        runOnUiThread(() -> {
            AlertDialog alertDialog = ToastHelper.showTipDialogNoShow((DataRecoverActivity.this), R.mipmap.chuchang_gray, R.string.cancel);
            showDialog(alertDialog);
            disMissDialogDelay(alertDialog, (3000));
        });
    }

    private void showRecoverConfirm(final int index) {
        runOnUiThread(() -> {
            dismissDialog((null));
            showExportProgress((0), (0));
            AlertDialog a = ToastHelper.showChooseDialogNoShow(getString(R.string.data_recovery_confirm), R.mipmap.ic_exclamation_mark,
                    getString(R.string.recover_data_alarm), getResources().getColor(R.color.button),
                    getString(R.string.confirm), getString(R.string.cancel), (DataRecoverActivity.this), new ToastHelper.OnDialogClickListener() {
                        @Override
                        public void onOKClickListener(View view) {
                            recoverExcel(index);
                        }

                        @Override
                        public void onCancelClickListener(View view) {

                        }
                    });
            showDialog(a);
        });
    }

    public void updateView(int counts, int remain) {
        showExportProgress(counts, remain);
    }

    ExportProgressDialog mExportProgressDialog;

    private void showExportProgress(final int count, final int remain) {
        if (mExportProgressDialog == null) {
            runOnUiThread(() -> {
                mExportProgressDialog = new ExportProgressDialog();
                mExportProgressDialog.showExportDialogNoShow((DataRecoverActivity.this),
                        (View view) -> {
                            if (recoverStatus) {
                                excelMa.stopExport();
                            } else {
                                DataRecoverActivity.this.finish();
                            }
                        }, count, remain, getString(R.string.data_recovering), getString(R.string.recovery_data));
                showDialog(mExportProgressDialog.mAlertDialog);
            });
        } else {
            mExportProgressDialog.update((this), count, remain);
        }
    }

    @Override
    public void onBackPressed() {
        if (!isRecovering) {
            DataRecoverActivity.this.finish();
        }
    }

    List<File> mFiles;

    private void getLocalFiles() {
        mFiles = Slog.getFiles(ExcelMa.getSavePath(), new ArrayList<>());
        initData(mFiles);
    }

    void initData(List<File> list) {
        //设置适配器
        myAdapter = new MyAdapter(list);
        myAdapter.setOnItemClickListener((View view, int position) -> {
        });
        mRecyclerView.setAdapter(myAdapter);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;
        TextView tv_file_size;
        TextView tv_end_time;
        ImageView ivSelect;
        ConstraintLayout cl_content;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_name);
            tv_file_size = itemView.findViewById(R.id.tv_file_size);
            tv_end_time = itemView.findViewById(R.id.tv_end_time);
            ivSelect = itemView.findViewById(R.id.iv_select);
            cl_content = itemView.findViewById(R.id.cl_content);
        }
    }

    static class MyAdapter extends RecyclerView.Adapter<ViewHolder> {
        List<File> mDataList;
        private OnItemClickListener mOnItemClickListener;
        int indexSelect = -1;

        MyAdapter(List<File> mList) {
            this.mDataList = mList;
        }

        int getSelectIndex() {
            return indexSelect;
        }

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

        @Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
            File f = mDataList.get(viewHolder.getAdapterPosition());
            String text = f.length() / (1024) + "kb";
            viewHolder.tv_file_size.setText(text);
            viewHolder.tvName.setText(f.getName());
            viewHolder.tv_end_time.setText(DateUtils.formatMilliesTimestamp(f.lastModified(), YYYY_MM_DD_HH_MM_SS));
            if (indexSelect == viewHolder.getAdapterPosition()) {
                viewHolder.ivSelect.setImageResource(R.mipmap.ic_selected);
            } else {
                viewHolder.ivSelect.setImageResource(R.mipmap.ic_default);
            }
            viewHolder.cl_content.setOnClickListener((View v) -> {
                indexSelect = viewHolder.getAdapterPosition();
                notifyDataSetChanged();
            });
        }

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

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

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