package com.usai.redant.raimage.PhotoList;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.usai.redant.redantmobile.R;
import com.usai.redant.util.RAUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PhotoGridActivity extends AppCompatActivity implements RAGridView.GridViewMeasure {

    private RAGridView gridView;
    private GridViewAdapter adapter;
    private Button deleteBtn;
    private ArrayList<HashMap<String,String>> photoDic;

    private static int land_col = 5;
    private static int portrait_col = 3;
    private int col;

    private boolean measuring;

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

        Intent intent = getIntent();
        ArrayList<String> photos = (ArrayList<String>) intent.getSerializableExtra("pic_list");
        photoDic = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < photos.size(); i++) { // 默认全部未选中

            HashMap<String,String> dic = new HashMap<String, String>();
            dic.put("path",photos.get(i));
            dic.put("delete","0");

            photoDic.add(dic);
        }


        gridView = (RAGridView) findViewById(R.id.photo_grid_view);
        gridView.measureWorker = this;


        deleteBtn = (Button)findViewById(R.id.grid_photo_delete_btn);
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Iterator<HashMap<String,String>> iterator = photoDic.iterator();
                while (iterator.hasNext()) {
                    HashMap<String,String> item = iterator.next();
                    int delete = Integer.valueOf(item.get("delete"));
                    if (delete == 1) {
                        // 删除文件
                        new File(item.get("path")).delete();
                        RAUtil.updateGallery(item.get("path"));
                        iterator.remove();
                        int index = photoDic.indexOf(item);
                    }
                }
                adapter.notifyDataSetChanged();

            }
        });


        int h = getWindowManager().getDefaultDisplay().getHeight();
        int w = getWindowManager().getDefaultDisplay().getWidth();


        if (w > h) {
            col = land_col;
        } else {
            col = portrait_col;
        }
        gridView.setNumColumns(col);

        Log.d("List", "onCreate: setAdapter");
        // 设置Adapter
        gridView.setAdapter(adapter = new GridViewAdapter());


        /**Action Bar*/
        ActionBar mActionBar = getSupportActionBar();
        mActionBar.setHomeButtonEnabled(true);
        mActionBar.setDisplayHomeAsUpEnabled(true);
        mActionBar.setTitle("RA Image");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("List", "onStart");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                finish();
            }
            break;
        }
        return true;
    }

    private void showPhotoPreview(int index) {
        ArrayList<String> photos = new ArrayList<String>();
        Iterator<HashMap<String,String>> iterator = photoDic.iterator();
        while (iterator.hasNext()) {
            HashMap<String,String> item = iterator.next();
            photos.add(item.get("path"));
        }
//        Toast.makeText(PhotoGridActivity.this,"Click" + index,Toast.LENGTH_LONG).show();
        Intent intent = new Intent(this,NewPhotoPreviewActivity.class);
        intent.putExtra("photos",(Serializable)photos);
        intent.putExtra("index",index);
        startActivity(intent);
    }



    /**缩小图片*/
    public Bitmap scaleImage(String path) {
        Bitmap source = BitmapFactory.decodeFile(path);

        int originWidth = source.getWidth();
        int originHeight = source.getHeight();

        int width = originWidth, height = originHeight;

        if (originHeight > 1024 || originWidth > 1024)
        {
            if (originWidth > originHeight)
            {
                width = 1024;
                height = originHeight * 1024 / originWidth;

            }
            else
            {

                height = 1024;
                width = originWidth * 1024 / originHeight;

            }
        }
        Bitmap scaled = Bitmap.createScaledBitmap(source, width, height, true);
        return scaled;
    }

    @Override
    public void measuring(boolean m) {
        this.measuring = m;
    }


    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**Adapter*/
    private class GridViewAdapter extends BaseAdapter {

        private class PhotoViewHolder {
            public ImageView photoView;
            public ImageButton checkBtn;

            public PhotoViewHolder(View view) {
                photoView = (ImageView)view.findViewById(R.id.photo_list_iv);
                checkBtn = (ImageButton)view.findViewById(R.id.photo_list_checkBtn);
            }
        }


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

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            /**系统多次调用以测量*/

            PhotoViewHolder holder = null;
            View cell;
            if (convertView == null) {
                cell = (View) LayoutInflater.from(PhotoGridActivity.this).inflate(R.layout.photo_list_item,null);
                holder = new PhotoViewHolder(cell);
                cell.setTag(holder);
            } else {
                cell = convertView;
                holder = (PhotoViewHolder)cell.getTag();
            }

            if (measuring == true) {
                measuring = false;
//                return cell;
            }


            final HashMap<String,String> item = photoDic.get(position);
            final String path = item.get("path");


//            Bitmap bitmap = scaleImage(path);

//            Log.d("Decode", "begin path: " + path);
//             Bitmap bitmap = BitmapFactory.decodeFile(path);
//            Log.d("Decode", "end path: " + path);
//
//            Bitmap scale = ThumbnailUtils.extractThumbnail(bitmap, 300, 300);
//
//            holder.photoView.setImageBitmap(scale);

            if (thumbPhotoIsExists(path)) {
                Bitmap bitmap = BitmapFactory.decodeFile(thumbFile(path).getAbsolutePath());
                holder.photoView.setImageBitmap(bitmap);
            } else {
                holder.photoView.setImageBitmap(null);
                final String filePath = path;
                final PhotoViewHolder photoHolder = holder;
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
//
//                        final Bitmap scale = ThumbnailUtils.extractThumbnail(bitmap, 300, 300);
//
//                        File thumbFile = thumbFile(filePath);
//                        savePhotoToFile(scale,thumbFile);
//
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                photoHolder.photoView.setImageBitmap(scale);
//                            }
//                        });
//                    }
//                }).start();

                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("Run", "begin " + filePath);

                        Bitmap scale = null;
                        if (thumbPhotoIsExists(filePath)) {
                            scale = BitmapFactory.decodeFile(thumbFile(filePath).getAbsolutePath());
                        } else {
                            Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                            scale = ThumbnailUtils.extractThumbnail(bitmap, 300, 300);
                            File thumbFile = thumbFile(filePath);
                            savePhotoToFile(scale,thumbFile);
                            bitmap.recycle();
                        }

                        final Bitmap scale_img = scale;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                photoHolder.photoView.setImageBitmap(scale_img);

                            }
                        });
                        Log.d("Run", "finish " + filePath);
                    }
                });
            }




            holder.checkBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_none));

            int delete = Integer.valueOf(item.get("delete"));
            if (delete == 1) {
                holder.checkBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_check));
            }

            final int idx = position;
            holder.checkBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ImageButton checkBtn = (ImageButton)v;
                    checkBtn.setSelected(!checkBtn.isSelected());
                    if (checkBtn.isSelected()) {
                        checkBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_check));
                        item.put("delete","1");
                        photoDic.set(idx,item);
                    } else  {
                        checkBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.check_none));
                        item.put("delete","0");
                        photoDic.set(idx,item);
                    }
                }
            });

            holder.photoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPhotoPreview(idx);
                }
            });



            /**解决Item被拉伸压缩*/
            int itemWidth = (int)(getResources().getDisplayMetrics().widthPixels -  (col + 1) * 10)  / col;
            int itemHeight = itemWidth;

            AbsListView.LayoutParams param = (AbsListView.LayoutParams) cell.getLayoutParams();

            if (param == null) {
                /**解决第一个Item不响应*/
                param = new AbsListView.LayoutParams(itemWidth, itemHeight);
            } else {
                param.width = itemWidth;
                param.height = itemHeight;
            }
            cell.setLayoutParams(param);

            Log.d("List", "Return Cell");
            return cell;
        }


    }

    private void savePhotoToFile(Bitmap bitmap, File photoFile) {
        if (photoFile == null || bitmap == null) {
            return;
        }
        try {

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(photoFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();

        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    private String photoDirectory() {

        String dir = Environment.getExternalStorageDirectory().getPath() + "/redant/.thumb/";
        File file = new File(dir);
        if (!file.exists()) {
            if (file.mkdirs()) {
                return dir;
            } else {
                return null;
            }
        }
        return dir;
    }

    private File thumbFile(String path) {
        File file = new File(path);
        String name = file.getName();
        String thumbDir = photoDirectory();
        if (thumbDir != null) {
            String thumbPath = thumbDir + name;
            return new File(thumbPath);
        }
        return null;
    }

    private boolean thumbPhotoIsExists(String path) {

        File thumbFile = thumbFile(path);
        if (thumbFile != null && thumbFile.exists()) {
            return true;
        }

        return false;
    }
}
