package com.usai.apex;

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

import com.usai.util.commonUtil;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class LocalDocumentActivity extends ListActivity
{
	public static final String FILETYPE ="pdf";
	private List<Map<String, Object>> getData()
	{
		List<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;
            for(int i = 0; i < files.length; i++)
            {
//				String filePath = files[i].getAbsolutePath();
				String fileName = files[i].getName();
				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);

            }
        }
		return list;
	}


	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		setContentView(R.layout.message_list);

		SimpleAdapter adapter = new DocumentsAdapter(this,
				getData(), R.layout.documents_list_item, new String[] { "title",
						"img" }, new int[] { R.id.tv_toolname, R.id.iv_thumb});
		setListAdapter(adapter);
		this.getListView().setBackgroundColor(Color.WHITE);		
		
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{
		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 class DocumentsAdapter extends SimpleAdapter
	{

//		private LayoutInflater	mInflater;
		@Override
		public View getView( int position, View convertView, ViewGroup parent)
		{
			convertView =super.getView(position, convertView, parent);
			// TODO Auto-generated method stub
//			convertView = mInflater.inflate(R.layout.announcement_item, null);// 根据布局文件实例化view

			ImageView iv = (ImageView)convertView.findViewById(R.id.iv_share);
			iv.setTag( (String) getData().get(position).get("title"));
			iv.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v)
				{
					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);//此处可发送多种文件
					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,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to)
		{
			
			super(context, data, resource, from, to);
			
//			this.mInflater = LayoutInflater.from(context);
			// TODO Auto-generated constructor stub
		}
		
	}
}
