package com.usai.apex.saved;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.usai.apex.R;
import com.usai.apex.pdf.PDFPreviewActivity;
import com.usai.apex.swipemenulistview.BaseSwipListAdapter;
import com.usai.apex.swipemenulistview.SwipeMenu;
import com.usai.apex.swipemenulistview.SwipeMenuCreator;
import com.usai.apex.swipemenulistview.SwipeMenuItem;
import com.usai.apex.swipemenulistview.SwipeMenuListView;
import com.usai.util.commonUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class SavedDocumentsFragment extends AMListFragment/* implements View.OnTouchListener*/ {
    class FileComparator2 implements Comparator<File> {

        @Override
        public int compare(File file1, File file2) {
            if (file1.lastModified() < file2.lastModified()) {
                return 1;// 最后修改的文件在前
            } else {
                return -1;
            }
        }
    }
    private class DocumentsAdapter extends BaseSwipListAdapter
    {

        class Holder {
            TextView message,time;
            ImageView iv,icon;


            Holder(View cell) {
                message = (TextView) cell.findViewById(R.id.tv_title);// 找某个控件
                time = (TextView) cell.findViewById(R.id.tv_detail);
                iv = (ImageView)cell.findViewById(R.id.iv_share);
                icon = (ImageView)cell.findViewById(R.id.iv_thumb);
                cell.setTag(this);
            }

        }

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

        @Override
        public Object getItem(int i) {
            return mList.get(i);
        }

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

        @Override
        public boolean getSwipEnableByPosition(int position) {
            return true;
        }

        //		private LayoutInflater	mInflater;
        @Override
        public View getView( int position, View convertView, ViewGroup parent)
        {

            Holder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.saved_doc, null);// 根据布局文件实例化view
                holder = new Holder(convertView);
            } else {
                holder = (Holder) convertView.getTag();
            }
            // TODO Auto-generated method stub
//			convertView = mInflater.inflate(R.layout.announcement_item, null);// 根据布局文件实例化view

//            ImageView iv = (ImageView)convertView.findViewById(R.id.iv_share);

            int rid = (int)mList.get(position).get("img");

            holder.icon.setImageResource(rid);
            holder.message.setText((String)mList.get(position).get("title"));
            holder.time.setText((String)mList.get(position).get("lastmodify"));


            holder.iv.setTag( (String) mList.get(position).get("title"));
            holder.iv.setOnClickListener(new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {

                    if(false)
                    {
                        Intent intent = new Intent(Intent.ACTION_SEND); // 启动分享发送的属性
                        intent.setType("text/plain"); // 分享发送的数据类型
                        intent.putExtra(Intent.EXTRA_TEXT, "email test"); // 分享的内容
                        startActivity(Intent.createChooser(intent,"abcdefg!!!!!!!"));// 目标应用选择对话框的标题
                    }
                    else

                    {
                        Intent share = new Intent(Intent.ACTION_SEND);
                        String filename = (String) v.getTag();
                        share.putExtra(Intent.EXTRA_STREAM,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/Apex Mobile/"+filename)));
                        String[] token = filename.split("\\.");
                        String ext = token[token.length-1];
                        share.setType("application/"+ext);//此处可发送多种文件
                        share.putExtra(Intent.EXTRA_TEXT, "test content text");   //附带的说明信息
                        share.putExtra(Intent.EXTRA_SUBJECT, "test subject");
                        share.putExtra(Intent.EXTRA_EMAIL, new String[]{"isbcd@hotmail.com","isbcd.zhangrui@gmail.com"});
                        share.putExtra(Intent.EXTRA_CC, new String[]{"ray.zhang@united-cn.net"});
                        startActivity(Intent.createChooser(share,getString(R.string.str_sendto)));
                    }


                }
            });
//			TextView title = (TextView) convertView.findViewById(R.id.tv_title);// 找某个控件
//			title.setText(result.getData().get(position).get("title")
//					.toString());// 给该控件设置数据(数据从集合类中来)
//			TextView content = (TextView) convertView
//					.findViewById(R.id.tv_content);
//			content.setText(result.getData().get(position).get("content")
//					.toString());
//			if (result.getData().get(position).get("image").toString().length() > 0)
//			{
//				byte[] gzipBuff = Base64.decode(result.getData().get(position)
//						.get("image").toString(), 0);
//
//				ByteArrayInputStream memstream = new ByteArrayInputStream(
//						gzipBuff, 0, gzipBuff.length);
//
//				ByteArrayOutputStream baos = new ByteArrayOutputStream(
//						gzipBuff.length);
//				ImageView iv_thumb = (ImageView) convertView
//						.findViewById(R.id.iv_thumb);
//				try
//				{
//					baos.write(gzipBuff);
//
//					Bitmap bmp = BitmapFactory.decodeStream(memstream);
//
//					// ImageView image = new ImageView(this);
//
//					iv_thumb.setImageBitmap(bmp);
//				}
//				catch (IOException e)
//				{
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//			// img.setBackgroundResource((Integer)jObject.get("img"));

            return convertView;
        }
        public DocumentsAdapter(Context context)
        {



//			this.mInflater = LayoutInflater.from(context);
            // TODO Auto-generated constructor stub
        }

    }
    public static final String FILETYPE ="pdf";
    public SavedDocumentsFragment() {
        // Required empty public constructor
    }

    private ArrayList<Map<String, Object>> getData()
    {
        ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();



        if(commonUtil.localdirExist())
        {
            File path = new File(Environment.getExternalStorageDirectory().getPath()+"/Apex Mobile");
            //返回文件夹中有的数据
            File[] files = path.listFiles();
            //先判断下有没有权限，如果没有权限的话，就不执行了
            if(null == files)
                return list;

            List<File> fileList = new ArrayList<File>();
//            String path = FileUtils.IMAGE_PATH;//文件夹路径
//            File file = new File(path);
//            if (file.exists() && file.isDirectory()) {
//                File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                    fileList.add(files[i]);
                }
            Collections.sort(fileList, new FileComparator2());




            for(int i = 0; i < fileList.size(); i++)
            {
//				String filePath = files[i].getAbsolutePath();
                String fileName = fileList.get(i).getName();
//                files[i].get
                String[] token = fileName.split("\\.");
                String ext = token[token.length-1];
                if(!FILETYPE.contains(ext))
                    continue;

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("title", fileName);
                map.put("ext", ext);
                if(ext.toLowerCase().equals("pdf"))
                    map.put("img", R.drawable.ic_pdf128);
                else
                    map.put("img", R.drawable.ic_file128);
                list.add(map);


                long time = fileList.get(i).lastModified();//返回文件最后修改时间，是以个long型毫秒数
                String ctime = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss").format(new Date(time));

                map.put("lastmodify", ctime);

                Log.d("file info", "last modify " + ctime);

//                files[i]

            }
        }
        return list;
    }
//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//
//
//
//        TextView textView = new TextView(getActivity());
//        textView.setText(R.string.hello_blank_fragment);
//        return textView;
//    }


    @Override
    public void onListItemClick(ListView l, View v, int position, long id)
    {

        String filename = (String) getData().get(position).get("title");
        String file=new File(Environment
                .getExternalStorageDirectory().getPath()
                + "/Apex Mobile/"
                + filename).getAbsolutePath();

        Intent myIntent = new Intent();
        myIntent = new Intent(getActivity(), PDFPreviewActivity.class);

        myIntent.putExtra("file",file);
        myIntent.putExtra("iscache",false);
        startActivity(myIntent);

        /*
        Log.d("FragmentList", "Item clicked: " + id);
        String filename = (String) getData().get(position).get("title");
        Intent intent = new Intent("android.intent.action.VIEW");

        intent.addCategory("android.intent.category.DEFAULT");

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Uri uri = Uri.fromFile(new File(Environment
                .getExternalStorageDirectory().getPath()
                + "/Apex Mobile/"
                + filename));

        intent.setDataAndType(uri, "application/"+(String) getData().get(position).get("ext"));
//	    startActivity(intent);
        startActivity(Intent.createChooser(intent,getString(R.string.str_openfile)));
//
*/
//		Intent intent = new Intent();
//		if(title.equals("Search documents online"))
//		{
//			intent.setClass(this, SearchListActivity.class);
//
//			intent.putExtra("function_name", "Download Document");
//			intent.putExtra("title", "Document Search");
//
//		}
//		else if(title.equals("View download documents"))
//		{
//			intent.setClass(this, AnnouncementActivity.class);
//			intent.putExtra("module_name", "Announcements");
//		}
//
//
//		startActivity(intent);

    }

    private ArrayList<Map<String, Object>> mList;
    private DocumentsAdapter mAdapter;

    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
//        adapter = new SavedDetailFragment.FavoritesAdapter(searchresult, getActivity());
//
//        getListView().setOnTouchListener(this);
//        setListAdapter(adapter);


        mList = getData();
//        SimpleAdapter adapter = new DocumentsAdapter(getActivity(),
//                getData(), R.layout.saved_doc, new String[] { "title",
//                "img","lastmodify" }, new int[] { R.id.tv_msg, R.id.iv_icon,R.id.tv_detail });
        mAdapter = new DocumentsAdapter(mContext);
        setListAdapter(mAdapter);
        getListView().setBackgroundColor(Color.WHITE);
        // this.getListView().setBackgroundColor(Color.WHITE);

        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set a icon
                deleteItem.setTitle("Delete");
                // set item title fontsize
                deleteItem.setTitleSize(18);
                // set item title font color
                deleteItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        // set creator
        mSwipeMenuListView.setMenuCreator(creator);

        // step 2. listener item click event
        mSwipeMenuListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {


                switch (index) {
                    case 0:
                        // delete
                        String filename = (String) getData().get(position).get("title");

                        File file = new File(Environment
                                .getExternalStorageDirectory().getPath()
                                + "/Apex Mobile/"
                                + filename);
                        if (file != null && file.exists()) {
                            file.delete();
                        }

                        File emailFile = new File(Environment
                                .getExternalStorageDirectory().getPath()
                                + "/Apex Mobile/"
                                + filename + ".email");
                        if (emailFile != null && emailFile.exists()) {
                            emailFile.delete();
                        }

                        mList.remove(position);
                        mAdapter.notifyDataSetChanged();

                        break;
                }
                return false;
            }
        });

        // set SwipeListener
        mSwipeMenuListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });

        // set MenuStateChangeListener
        mSwipeMenuListView.setOnMenuStateChangeListener(new SwipeMenuListView.OnMenuStateChangeListener() {
            @Override
            public void onMenuOpen(int position) {
            }

            @Override
            public void onMenuClose(int position) {
            }
        });

    }
//
//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
//        return false;
//    }

    public void clear() {

//        int count = mList.size();
//        for (int i = count - 1; i >= 0; i--) {
//            String filename = (String) getData().get(i).get("title");
//
//            File file = new File(Environment
//                    .getExternalStorageDirectory().getPath()
//                    + "/Apex Mobile/"
//                    + filename);
//            if (file != null && file.exists()) {
//                file.delete();
//            }
//            mList.remove(i);
//        }
//        mAdapter.notifyDataSetChanged();


        File dir = new File(Environment.getExternalStorageDirectory().getPath()+ "/Apex Mobile/");
        deleteFile(dir);
        mList.clear();
        mAdapter.notifyDataSetChanged();
    }

    private void deleteFile(File deleteFile) {

        if (deleteFile != null && deleteFile.isDirectory()) {

            File[] files = deleteFile.listFiles();
            for (int i = 0; i < files.length; i++) {

                File file = files[i];
                if (file.isDirectory()) {
                    deleteFile(file);
                }

                file.delete();

            }
        }
    }
}
