package com.cwbuyer.main;

import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.format.ItemData;
import com.cwbuyer.lib.AsyncImageFileLoader;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.lib.AsyncImageFileLoader.ImageCallback;
import com.pwbuyer.main.R;

@SuppressLint("InflateParams")
public class AShowSearch extends Activity{

	ListView mListView = null;
	List<ItemData> mListData = null;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_search_layout);
		// get String
		String search = getIntent().getStringExtra("search_item");
		if(search != null && search.length() > 0){
			mListData = getItems(search);
			if(mListData != null && mListData.size() > 0){
				setTitle("搜尋結果共 (" + mListData.size() + ") 筆");
				ItemAdapter adapter = new ItemAdapter(this);
				mListView = (ListView)findViewById(R.id.listview);
				mListView.setAdapter(adapter);
				mListView.setOnItemClickListener(new OnItemClickListener(){
					@Override
					public void onItemClick(AdapterView<?> arg0, View view,
							int position, long arg3) {
						Intent intent = new Intent();
						// 這部份可能會依照不同 db 去修改  --------------------Notice!
						intent.putExtra("search_mid", mListData.get(position).nMid);
						AShowSearch.this.setResult(RESULT_OK, intent);
						finish();
					}
				});
				((Button)findViewById(R.id.btn_exit)).setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						finish();
					}
				});
			}else{
				Toast.makeText(this, "錯誤！找不到物品", Toast.LENGTH_SHORT).show();
				finish();
			}
		}else{
			finish();
		}
	}
	
	private List<ItemData> getItems(String search){
		SQLiteDatabase db = Utilis.getDB(this);
		List<ItemData> listData = null;
		if(db != null){
			try{
				Cursor cursor = db.rawQuery(search, null);
				if (cursor != null) {
					if (cursor.getCount() > 0) {
						listData = new ArrayList<ItemData>();
						cursor.moveToFirst();
						for (int k = 0; k < cursor.getCount(); k++) {
							ItemData data = DBUtil.CItem.parseDetailData(cursor);
							listData.add(data);
							cursor.moveToNext();
						}
					}
					cursor.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				db.close();
			}
		}
		return listData;
	}
	
	// 搜尋指定的項目 是否有資料回傳
		@SuppressWarnings("unused")
		private List<ItemData> getSearchItem(SQLiteDatabase db, String param, String key){
			List<ItemData> listData = null;
			try{
				if(key == null || key.length() <= 0){
					return null;
				}
				StringBuffer buf = new StringBuffer();
//				buf.append("Select * from qdetail where ");
				buf.append("Select B.Name,A.* from qdetail A inner join qc_country B on A.COUNTRY=B._ID WHERE ");
//				select B.Name,A.* from qdetail A inner join qc_country B on A.COUNTRY=B._ID WHERE A.SUPPLY like '%"
				if(param.equalsIgnoreCase("P5") != true){
					buf.append(param).append(" like '%").append(key).append("%'");
				}else{
					buf.append("P5=").append(key);
				}
				Cursor cursor = db.rawQuery(buf.toString(), null);
				if (cursor != null) {
					if (cursor.getCount() > 0) {
						listData = new ArrayList<ItemData>();
						cursor.moveToFirst();
						for (int k = 0; k < cursor.getCount(); k++) {
							ItemData data = DBUtil.CItem.parseDetailData(cursor);
							listData.add(data);
							cursor.moveToNext();
						}
					}
					cursor.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return listData;
		}
	
	public class ItemAdapter extends BaseAdapter{

		private LayoutInflater mInflater;
		private AsyncImageFileLoader asyncImageFileLoader;
		
		public ItemAdapter(Context cnt){
			mInflater = LayoutInflater.from(cnt);
			asyncImageFileLoader = new AsyncImageFileLoader();
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mListData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_pic);
				holder.textGoodsNo = (TextView) convertView.findViewById(R.id.text_goodsno);
				holder.textImpo = (TextView) convertView.findViewById(R.id.text_impo);
				holder.textName = (TextView) convertView.findViewById(R.id.text_name);
				holder.textNumber = (TextView) convertView.findViewById(R.id.text_number);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_money);
				holder.textCountry = (TextView) convertView.findViewById(R.id.text_country);
				holder.textCompany = (TextView) convertView.findViewById(R.id.text_company);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			ItemData data = mListData.get(position);
			
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.0");
//			ItemData data = mList.get(position);
	    		String tag = data.pic1 + position;
	    		holder.imageItem.setTag(tag);
			if(data.pic1 != null && data.pic1.length() > 0){
//				holder.imageItem.setImageBitmap(Utilis.getSmallPic(data.pic1));
    	    	  Bitmap cachedBitmap = asyncImageFileLoader.loadBitmap(data.pic1, 70, 96, tag,new ImageCallback() {  
		          public void imageCallback(Bitmap imageBitmap, String imageFile, String tag) {
		                    // 利用檔案名稱找尋當前mHolder.icon
		                ImageView imageViewByTag = (ImageView) mListView.findViewWithTag(tag);  
		                if (imageViewByTag != null) {  
		                if(imageBitmap != null)
		                	imageViewByTag.setImageBitmap(imageBitmap);
		                }
		          }  
	          });  
	          if(cachedBitmap != null){
	            holder.imageItem.setImageBitmap(cachedBitmap);
	          }
				
			}else{
				holder.imageItem.setImageResource(R.drawable.img_empty);
			}
			holder.textName.setText(data.goodsname);
			holder.textGoodsNo.setText(data.GoodsNo);
			holder.textImpo.setText("總件數 " + data.nTotalCount);
			holder.textMoney.setText("$" + myformat.format((data.nTotalCount * data.dP1))+"/"+ myformat.format((data.nTotalCount * data.dP0)));
			holder.textCountry.setText(data.batch);
			holder.textCompany.setText(data.supply);
			holder.textNumber.setText(data.sourceNo);
			return convertView;
		}
		
		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			TextView textGoodsNo;
			TextView textImpo;
		}
	}
}
