package com.github.material.monitor.demo.mock;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.github.material.monitor.FrameRecord;
import com.github.material.monitor.MaterialMonitor;
import com.github.material.monitor.MaterialStyle;
import com.github.material.monitor.demo.R;

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

/**
 * 本地截帧图库（对接文档 §5.8 {@code getRecords} / {@code deleteRecord}）。
 *
 * <p>用于查看仍保留在磁盘上的 JPEG：包括上报排队中、上报失败可重试、或终态失败尚未清理前的文件。
 * 上报成功后库会删除本地文件，图库中不再显示。</p>
 */
public final class MockGalleryActivity extends Activity {

    private static final String FILTER_ALL = "all";

    private final List<FrameRecord> records = new ArrayList<FrameRecord>();
    private MaterialStyle currentStyle;
    private FrameGridAdapter adapter;
    private TextView emptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mock_gallery);

        findViewById(R.id.tv_gallery_title).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        emptyView = findViewById(R.id.tv_empty);

        Spinner spinner = findViewById(R.id.sp_style);
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_dropdown_item, buildStyleLabels());
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    currentStyle = null;
                } else {
                    currentStyle = MaterialStyle.values()[position - 1];
                }
                refreshData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        GridView gridView = findViewById(R.id.grid_view);
        adapter = new FrameGridAdapter();
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FrameRecord record = records.get(position);
                if (record.file == null || !record.file.exists()) {
                    Toast.makeText(MockGalleryActivity.this, R.string.gallery_file_missing, Toast.LENGTH_SHORT).show();
                    refreshData();
                    return;
                }
                Intent intent = new Intent(MockGalleryActivity.this, MockFramePreviewActivity.class);
                intent.putExtra(MockFramePreviewActivity.EXTRA_FILE_PATH, record.file.getAbsolutePath());
                startActivity(intent);
            }
        });
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final FrameRecord record = records.get(position);
                new AlertDialog.Builder(MockGalleryActivity.this)
                        .setMessage(R.string.gallery_delete_confirm)
                        .setPositiveButton(R.string.gallery_delete_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                boolean ok = MaterialMonitor.get().deleteRecord(record);
                                Toast.makeText(MockGalleryActivity.this,
                                        ok ? R.string.gallery_delete_success : R.string.gallery_delete_failed,
                                        Toast.LENGTH_SHORT).show();
                                refreshData();
                            }
                        })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
                return true;
            }
        });

        spinner.setSelection(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
    }

    private List<String> buildStyleLabels() {
        List<String> names = new ArrayList<String>();
        names.add(getString(R.string.gallery_filter_all));
        for (MaterialStyle style : MaterialStyle.values()) {
            names.add(style.getFolderName());
        }
        return names;
    }

    private void refreshData() {
        records.clear();
        if (currentStyle == null) {
            for (MaterialStyle style : MaterialStyle.values()) {
                appendExistingFiles(MaterialMonitor.get().getRecords(style));
            }
            Collections.sort(records, new Comparator<FrameRecord>() {
                @Override
                public int compare(FrameRecord o1, FrameRecord o2) {
                    return Long.compare(o2.createTime, o1.createTime);
                }
            });
        } else {
            appendExistingFiles(MaterialMonitor.get().getRecords(currentStyle));
        }
        adapter.notifyDataSetChanged();
        emptyView.setVisibility(records.isEmpty() ? View.VISIBLE : View.GONE);
    }

    /** 仅展示仍有本地 JPEG 的条目（url-only 无 file；上报成功后会删文件） */
    private void appendExistingFiles(List<FrameRecord> source) {
        if (source == null || source.isEmpty()) {
            return;
        }
        for (FrameRecord record : source) {
            File file = record.file;
            if (file != null && file.exists() && file.length() > 0L) {
                records.add(record);
            }
        }
    }

    private final class FrameGridAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return records.size();
        }

        @Override
        public Object getItem(int position) {
            return records.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_frame_grid, parent, false);
                holder = new ViewHolder();
                holder.imageView = (ImageView) convertView.findViewById(R.id.iv_frame);
                holder.textView = (TextView) convertView.findViewById(R.id.tv_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            FrameRecord record = records.get(position);
            holder.imageView.setImageBitmap(BitmapFactory.decodeFile(record.file.getAbsolutePath()));
            String label = record.style != null ? record.style.getFolderName() : "";
            if (record.file != null) {
                label = label + "\n" + record.file.getName();
            }
            if (record.uploadTaskId != null && record.uploadTaskId.length() > 0) {
                label = label + "\ntask:" + record.uploadTaskId;
            }
            holder.textView.setText(label);
            return convertView;
        }
    }

    private static final class ViewHolder {
        ImageView imageView;
        TextView textView;
    }
}
