package com.cwbuyer.lib;

import java.io.File;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import com.cwbuyer.format.DefaultData;
import com.pwbuyer.main.R;
import com.cwbuyer.main.APos;
import com.cwbuyer.main.ManageAccount.AccountData;
import com.cwbuyer.main.QCustff.QCustfMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("DefaultLocale")
@SuppressWarnings("deprecation")
public class GalleryViewC extends Activity {

	private Gallery mGallery01;
	@SuppressWarnings("unused")
	private LinearLayout nLinear;
	private ImageView mImage;
	private ImageButton mImgBtnSearch;
	private ImageButton mImgBtnRobk;
	private EditText mEdSearch;
	private TextView mTextView01;
	private TextView mTextView02;
	private TextView mTextView03;
	private TextView mTextView04;
	private TextView mTextView05;
	private TextView mTextView06;
	private TextView mTextView07;
	private TextView mTextView08;
	private TextView mTextView09;
	private TextView mTextView10;
	
	//交易價別方式 千萬不可以在第一時間就以 getResources().getText(R.string.str.....)方式帶入
	private static final String[] tradeStr = { "","","","","",""};
	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+	 File.separator + "CWBuyer"  ;

	private ArrayList<String> mCountryList = new ArrayList<String>();
	private ArrayList<Integer> mCountryIdList = new ArrayList<Integer>();
	private ArrayList<String> mCountryIcon = new ArrayList<String>();	
	private ArrayList<String> mAccList = new ArrayList<String>();
	private ArrayList<Integer> mAccIdList = new ArrayList<Integer>();
	
	LinkedList<String> mSizeLink = new LinkedList<String>();
	LinkedList<String> mColorLink = new LinkedList<String>();
	
	private LinkedList<AccountData> mAccountList = null;
	private String[] mAccount;
	private int[] mAccountid;

	private DefaultData mDefaultData = null; // 採購參數

	String[] pKind={"廠商資料","專櫃資料","會員資料","櫃員資料","保留資料","保留資料"};

	String mKind =null; //單別 1020304050	
	int nKind=0; //單別 1020304050

	
	
	int version = 1;
	int records = 0;
	int positions = 0;
	String strRes = "";
	private String[] Aid; //商品編號 MID	
	private String[] Apicstr; //圖檔名稱
	int Wheight;
	int Wwidth;  		
	
	Bundle bundle;

	/** Called when the activity is first created. */
	@SuppressWarnings("unused")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;
		
		setContentView(R.layout.galleryc);
		mGallery01 = (Gallery) findViewById(R.id.myGallery21);
		mImage = (ImageView) findViewById(R.id.imageView205);
		mImgBtnSearch = (ImageButton) findViewById(R.id.imageButton25);		
		mImgBtnRobk = (ImageButton) findViewById(R.id.imageButton26);
		mEdSearch =(EditText)findViewById(R.id.edSearchp);
		nLinear=(LinearLayout)findViewById(R.id.liner_face);
		if (Wwidth<=480 && Wheight<=800  ) {// GI9000
			//270 350 120
			mImage.getLayoutParams().width=Wwidth;
			mImage.getLayoutParams().height=Wwidth-100;
			mGallery01.getLayoutParams().height=120;
		}
		else  if ((Wwidth==540 && Wheight==960  ) ||  (Wwidth==800 && Wheight==1280  )) {// HTC EVO 3D G_NOTE
			//330 450 120
			mImage.getLayoutParams().width=Wwidth;
			mImage.getLayoutParams().height=Wwidth;
			mGallery01.getLayoutParams().height=120;
		} 
		else if ((Wwidth==600 && Wheight==976) ||  (Wwidth==480 && Wheight==764)) {//平板 GTP3100 A10
			//380 500 120
			mImage.getLayoutParams().width=Wwidth;
			mImage.getLayoutParams().height=Wwidth;
			mGallery01.getLayoutParams().height=120;			
		} else { //其餘 手機 假設手機尺寸愈大
			//330 450 120
			mImage.getLayoutParams().width=Wwidth;
			mImage.getLayoutParams().height=Wwidth;
			mGallery01.getLayoutParams().height=120;
		}

//    	Toast.makeText(GalleryView.this,"螢幕寬度="+mImage.getLayoutParams().width+"螢幕高度="+mImage.getLayoutParams().height , Toast.LENGTH_SHORT).show();		

    	mTextView01 = (TextView) findViewById(R.id.textViewp1);
		mTextView02 = (TextView) findViewById(R.id.textViewp2);
		mTextView03 = (TextView) findViewById(R.id.textViewp3);
		mTextView04 = (TextView) findViewById(R.id.textViewp4);
		mTextView05 = (TextView) findViewById(R.id.textViewp5);
		mTextView06 = (TextView) findViewById(R.id.textViewp6);
		mTextView07 = (TextView) findViewById(R.id.textViewp7);
		mTextView08 = (TextView) findViewById(R.id.textViewp8);
		mTextView09 = (TextView) findViewById(R.id.textViewp9);
		mTextView10 = (TextView) findViewById(R.id.textViewp10);

//		交易價別方式設定 **千萬不可在陣列中一開始就使用轉址參考型別 LINE_51
	   	String btns=null;
	   	String[] bttns;
     	btns=Utilis.getIni(this,"SYS","TRADENAME",9);
	   	bttns = btns.split("!&!");
		tradeStr[0] = bttns[0];		tradeStr[1] = bttns[1];		tradeStr[2] = bttns[2];		tradeStr[3] = bttns[3];		tradeStr[4] = bttns[4];		tradeStr[5] = bttns[5]; 
				
		//歷史價  TRADENAME
     	btns=Utilis.getIni(this,"SYS","CKIND",9);
	   	bttns = btns.split("!&!");
		pKind[0] = bttns[0];		pKind[1] = bttns[1];		pKind[2] = bttns[2];		pKind[3] = bttns[3];		pKind[4] = bttns[4];		pKind[5] = bttns[5]; 

//		String custno=null; //客戶編號
//      int locates = Utilis.valuesInt(arrayW[1]); //起始位置 "12345,0,0"
//      int state=Utilis.valuesInt(arrayW[2]); // "1"要開啟查詢欄 "0"純粹LIST_ONLY
		
		nKind = getIntent().getIntExtra("qcust_qkind", APos.PItemKind.TR30);
		mKind=""+nKind;
		mKind=mKind.substring(0,1)+"0";  //永遠取整數,本功能只用在QCUST的基本檔的傳呼
		String custno= getIntent().getStringExtra("qcust_key"); //所要查詢的項目 這是一個重要的關鍵值
		int locates= getIntent().getIntExtra("qcust_locate",0); //
		int state = getIntent().getIntExtra("qcust_mode", QCustfMode.NORMAL); //0普 1啟動查詢欄
		
		//交易價別方式 千萬不可以在第一時間就以 getResources().getText(R.string.str.....)方式帶入
		setTitle(getResources().getText(R.string.app_name).toString()+pKind[(nKind/10)-1]+"_速查流覽");		
		getCountryData(this);
		getDefaultData();
		
	       mAccountList = DBUtil.CAccount.getAccountData(this);
	        if(mAccountList.size() > 0){
	        	mAccount = new String[mAccountList.size()];
	        	mAccountid = new int[mAccountList.size()];
	        	for(int i = 0; i < mAccountList.size(); i++){
	        		mAccount[i] = mAccountList.get(i).strShowInfo;
	        		mAccountid[i] = mAccountList.get(i).nID;
	        	}
	        }else{
	        	mAccount = new String[]{"無"};
	        	mAccountid = new int[]{0};
	        }
		
        SQLiteDatabase db = Utilis.getDB(this);
		Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select * from qcust");
		mySqlBuf.append(" where TR='"+mKind+"' order by CUSTNAME DESC LIMIT 1000");		
		cs = db.rawQuery(mySqlBuf.toString(), null);

					if (cs.getCount() > 0) {
						
						updateListView(cs);
						
//						if (locates<cs.getCount()){Display(locates);} else {Display(0);}
						Display(0);
						if (cs.getCount() >= 1000) {
							Toast.makeText(GalleryViewC.this,"超過1000筆的部分無法顯示!請下次縮小範圍!" , Toast.LENGTH_SHORT).show();							
						}
						db.close();	
				} else {
					db.close();
					finish();
					}
			if (state==QCustfMode.SEARCH){ mEdSearch.setVisibility(View.VISIBLE);}	
		/* 設定一個itemclickListener事件 */
		mGallery01.setOnItemClickListener(new Gallery.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				
				Display(position);
				positions = position;
			}
		});

//查詢 優先順序為 1.貨號 2.品名 3.類別 limit 1000為最大值否則請縮小範圍		
		mImgBtnSearch.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mEdSearch.isShown()){
//					mEdSearch.setVisibility(View.INVISIBLE);					
				}else {
					mEdSearch.setVisibility(View.VISIBLE);	
				}
				if (mEdSearch.length()>0){	searched();}
        		mEdSearch.setText("");					
				
//            		setupViews();

			}
		});
		
//回復 batch mid
		mImgBtnRobk.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		        SQLiteDatabase db = Utilis.getDB(GalleryViewC.this);
				Cursor cs = null;
				StringBuffer mySqlBuf = new StringBuffer();
				mySqlBuf.append("select * from qcust");
				mySqlBuf.append(" where TR='"+mKind+"' order by CUSTNAME DESC LIMIT 1000");
				cs = db.rawQuery(mySqlBuf.toString(), null);

							if (cs.getCount() > 0) {
								
								updateListView(cs);
								
//								if (locates<cs.getCount()){Display(locates);} else {Display(0);}
								Display(0);
								if (cs.getCount() >= 1000) {
									Toast.makeText(GalleryViewC.this,"超過1000筆的部分無法顯示!請下次縮小範圍!" , Toast.LENGTH_SHORT).show();							
								}
								db.close();	
						} else {
							db.close();
							finish();
							}

			}
		});
		
	}		
	

	private List<String> ChkPic() {
		/* 設定目前所在路徑 */
		List<String> it = new ArrayList<String>();
		/* 將所有檔案加入ArrayList中 */
		for (int i = 0; i < records; i++) {
			if (getImageFile(Apicstr[i]))
				it.add(Apicstr[i]);
			else {it.add(filepath+"/0916961962.png");}
		}
		return it;
	}

	private boolean getImageFile(String fName) {
		boolean re;

		/* 取得副檔名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 依附檔名的類型決定MimeType */
		if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			re = true;
		} else {
			re = false;
		}
		return re;
	}

	private void searched(){
		//將鍵盤收起來
  		 InputMethodManager m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
         m.hideSoftInputFromWindow(mEdSearch.getWindowToken(), 0);               		
			
        SQLiteDatabase db = Utilis.getDB(this);
        StringBuffer mySqlBuf = new StringBuffer();
 		mySqlBuf.append("select * from qcust");
 		mySqlBuf.append(" where TR='"+mKind+"' and CUSTNO  like '%" + mEdSearch.getText() + "%' order by _ID DESC LIMIT 1000" );

		Cursor cs = null;
		int catched = 0;
		cs = db.rawQuery(mySqlBuf.toString(), null);
		if (cs.getCount()>0){
			catched=1;
			updateListView(cs);
			Display(0);
		}
		if (catched==0) {
	        mySqlBuf.delete(0, mySqlBuf.length());
	 		mySqlBuf.append("select * from qcust");
	 		mySqlBuf.append(" where TR='"+mKind+"' and CUSTNAME  like '%" + mEdSearch.getText() + "%' order by _ID DESC LIMIT 1000" );
			cs = null;
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				catched=1;
				updateListView(cs);
				Display(0);
			}	
		}
		if (catched==0) {
	        mySqlBuf.delete(0, mySqlBuf.length());
	 		mySqlBuf.append("select * from qcust");
	 		mySqlBuf.append(" where TR='"+mKind+"' and MOBIL  like '%" + mEdSearch.getText() + "%' order by _ID DESC LIMIT 1000" );
			cs = null;
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				catched=1;
				updateListView(cs);
				Display(0);
			}	
		} 

		if (catched==0) {
	        mySqlBuf.delete(0, mySqlBuf.length());
	 		mySqlBuf.append("select * from qcust");
	 		mySqlBuf.append(" where TR='"+mKind+"' and EMAIL  like '%" + mEdSearch.getText() + "%' order by _ID DESC LIMIT 1000" );
			cs = null;
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				catched=1;
				updateListView(cs);
				Display(0);
			}	
		} 
		
		
		if(catched<=0){
			Toast.makeText(GalleryViewC.this,"查無此會員!" , Toast.LENGTH_SHORT).show();							
		}
	 db.close();	
	}
	/* 改寫BaseAdapter自訂一ImageAdapter class */
	public class ImageAdapter extends BaseAdapter {
		/* 宣告變數 */
		int mGalleryItemBackground;
		private Context mContext;
		private List<String> lis;

		/* ImageAdapter的建構子 */
		public ImageAdapter(Context c, List<String> li) {
			mContext = c;
			lis = li;
			/*
			 * 使用在res/values/attrs.xml中的<declare-styleable>定義 的Gallery屬性.
			 */
			TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
			/* 取得Gallery屬性的Index id */
			mGalleryItemBackground = a.getResourceId(
					R.styleable.Gallery_android_galleryItemBackground, 0);
			/* 讓物件的styleable屬性能夠反覆使用 */
			a.recycle();
		}

		/* 一定要覆寫的方法getCount,傳回圖片數目 */
		public int getCount() {
			return lis.size();
		}

		/* 一定要覆寫的方法getItem,傳回position */
		public Object getItem(int position) {
			return position;
		}

		/* 一定要覆寫的方法getItemId,傳回position */
		public long getItemId(int position) {
			return position;
		}

		/* 一定要覆寫的方法getView,傳回一View物件 */
		@SuppressWarnings("unused")
		public View getView(int position, View convertView, ViewGroup parent) {
			/* 產生ImageView物件 */
			ImageView i = new ImageView(mContext);
			/* 設定圖片給imageView物件 */
//			Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString());
			try
			{
				Bitmap bm = Utilis.getLimitBitmap(lis.get(position).toString(), 80, 80);
				i.setImageBitmap(bm);
		
			}catch(Exception e){
				Bitmap	bm = Utilis.getLimitBitmap(filepath+"/0916961962.png",80,80);
			}finally{
				
			}		

			/* 重新設定圖片的寬高 */
			i.setScaleType(ImageView.ScaleType.FIT_XY);
			/* 重新設定Layout的寬高 */
			if (Wwidth<=480 && Wheight<=800  ) {// GI9000
				//200 230 100
				i.setLayoutParams(new Gallery.LayoutParams(100, 90));
			}else {
				i.setLayoutParams(new Gallery.LayoutParams(100, 120));				
				}
			/* 設定Gallery背景圖 */
			i.setBackgroundResource(mGalleryItemBackground);
			/* 傳回imageView物件 */
			return i;
		}
	}
	
	
	private void updateListView(Cursor cs) {

		int record = 0;
		if (cs.getCount() > 0) {
			Aid = new String[cs.getCount()];
			Apicstr = new String[cs.getCount()];
			
//			cs.moveToFirst();
			while (cs.moveToNext()) {
				Aid[record] = cs.getString(cs.getColumnIndex("_ID"));
				Apicstr[record] = cs.getString(cs.getColumnIndex("PIC"));				
				record++;
			}

		}

		records = record;

		if (records>0) {		

		/* 新增一ImageAdapter並設定給Gallery物件 */
		mGallery01.setAdapter(new ImageAdapter(this, ChkPic()));		
		} else 
		{finish();}
		// if (dbHelper != null && dbHelper.getReadableDatabase().isOpen()) {
		// dbHelper.close(); }

	}

	// 取得預設參數
	private void getDefaultData(){
    	SQLiteDatabase db = Utilis.getDB(this);
    	if(db != null){
			Cursor cursor = db.rawQuery("select * from qc_default", null);
			if(cursor != null){
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						mDefaultData = new DefaultData();
						mDefaultData.nCountry = cursor.getInt(cursor.getColumnIndex("COUNTRY"));
						mDefaultData.dBillRate = cursor.getDouble(cursor.getColumnIndex("BILLRATE"));
						mDefaultData.batch = cursor.getString(cursor.getColumnIndex("BATCH"));
						mDefaultData.factno = cursor.getString(cursor.getColumnIndex("FACTNO"));
						mDefaultData.nItemState = cursor.getInt(cursor.getColumnIndex("STATE"));
						mDefaultData.nSourceNumber = cursor.getInt(cursor.getColumnIndex("SOURCENO"));
						mDefaultData.nItemProduct = cursor.getInt(cursor.getColumnIndex("PRODUCT"));
						mDefaultData.nItemFirst = cursor.getInt(cursor.getColumnIndex("ITEMFIRST"));
						mDefaultData.nSeason = cursor.getInt(cursor.getColumnIndex("SEASON"));
						mDefaultData.nYear = cursor.getInt(cursor.getColumnIndex("YEAR"));
						mDefaultData.employ = cursor.getString(cursor.getColumnIndex("EMPLOY"));
						mDefaultData.nAccountId = cursor.getInt(cursor.getColumnIndex("ACCOUNT"));
						mDefaultData.nHid = cursor.getString(cursor.getColumnIndex("HID"));
					}
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					cursor.close();
				}
			}
			db.close();
    	}
    }
	
	
//事先整理出產地國別	
	public void getCountryData(Context context){
		if(mCountryIdList != null){
			mCountryIdList.clear();
		}
		if(mCountryList != null){
			mCountryList.clear();
		} 
		
		if(mCountryIcon != null){
			mCountryIcon.clear();
		}
		
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cursor = db.rawQuery("select _ID,NAME,PIC from qc_country order by _ID", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						int id = cursor.getInt(cursor.getColumnIndex("_ID"));
						String pic = cursor.getString(cursor.getColumnIndex("PIC"));
						String name = cursor.getString(cursor.getColumnIndex("NAME"));
						mCountryIdList.add(id);
						mCountryIcon.add(pic);
						mCountryList.add(name);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}


	
	
	public void getAccount(Context context){
		if(mAccList != null){
			mAccList.clear();
		}
		if(mAccIdList != null){
			mAccIdList.clear();
		}
		SQLiteDatabase dbs = Utilis.getDB(context);
		Cursor cursor = dbs.rawQuery("select acctext,_id from qc_account order by _id", null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					for(int i = 0; i < cursor.getCount(); i++){
						String name = cursor.getString(cursor.getColumnIndex("acctext"));
						int id = cursor.getInt(cursor.getColumnIndex("_id"));
						mAccList.add(name);
						mAccIdList.add(id);
						cursor.moveToNext();
					}
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		dbs.close();
		dbs = null;
	}
	
	
	private void Display(int positionid) {
		int position = positionid;
        SQLiteDatabase db = Utilis.getDB(this);		
		Cursor cs = null;
		StringBuffer mySqlBuf = new StringBuffer();
		mySqlBuf.append("select * from qcust");
		mySqlBuf.append(" where TR='"+mKind+"' and _ID=" + Aid[position]);
    
		cs = db.rawQuery(mySqlBuf.toString(), null);
		cs.moveToFirst();
		if (cs.getCount()>0){
			mTextView01.setText(cs.getString(cs.getColumnIndex("CUSTNO")));		
			mTextView02.setText(cs.getString(cs.getColumnIndex("CUSTNAME")));
       		mTextView03.setText(cs.getString(cs.getColumnIndex("BANKNAME"))); //銀行
			
			int gcountry= cs.getInt(cs.getColumnIndex("COUNTRY"));   //代號需轉換為文字
				int cindex = mCountryIdList.indexOf(gcountry);
				if(cindex>=0){mTextView04.setText(mCountryList.get(cindex));}
				else {
					mTextView04.setText(cs.getString(cs.getColumnIndex("COUNTRY")));
				}
		
			mTextView05.setText(cs.getString(cs.getColumnIndex("MOBIL")));
			mTextView06.setText(cs.getString(cs.getColumnIndex("EMAIL")));
			//trade 交易方式 0外幣 1成本 2中盤 3批發 4網購 5零售
			int gtrade =cs.getInt(cs.getColumnIndex("TRADETYPE"));
			mTextView07.setText(tradeStr[gtrade]);
			  
			mTextView08.setText(""+cs.getString(cs.getColumnIndex("DISCOUNT"))+"%");
			mTextView09.setText(""+cs.getString(cs.getColumnIndex("ADDRESS")));
			mTextView10.setText(""+cs.getString(cs.getColumnIndex("PS")));
		
        	if(Apicstr[position] != null && Apicstr[position].length() > 0){
				Bitmap bitmap = Utilis.getLimitBitmap(Apicstr[position], 320, 480);
				if (bitmap != null) {
					Bitmap reflactionBitmap;
					reflactionBitmap = createReflectionBitmap(bitmap);
					mImage.setImageBitmap(reflactionBitmap);
					AnimationSet animation = new AnimationSet(true);
					animation.addAnimation(new AlphaAnimation(0.0F, 1.0F));
					animation.addAnimation(new TranslateAnimation(30, 0, 10, 0));
//					animation.addAnimation(new RotateAnimation(320,360, mImage.getWidth()/2.0F,mImage.getHeight()/2.0F));
					animation.addAnimation(new RotateAnimation(320,360, 0,0));					
					animation.setDuration(1000);
					mImage.startAnimation(animation);
//取得手機背景  nLinear.setBackgroundDrawable(getWallpaper());
//					nLinear.startAnimation(animation);
				} else {
					mImage.setImageResource(R.drawable.dsc010892);
				}
        	} else mImage.setImageResource(R.drawable.dsc010892);
		} //>0
		db.close();
	}

   	public int[] toInt(Set<Integer> set) {
	    		int[] a = new int[set.size()];
	    		int i = 0;
	    		for (Integer val : set)
	    			a[i++] = val;
	    		return a;
   	}
	        
	public static Bitmap createReflectionBitmap(Bitmap src) {
		// 原始圖片與反射圖片的邊界
		int margin = 4;
		int width = src.getWidth();
		int height = src.getHeight();

		// 用來做上下顛倒的Matrix
		Matrix matrix = new Matrix();
		matrix.preScale(1.0f, -1.2f);

		// 以原始圖片下半部顛倒過來產生Bitmap
		Bitmap reflection;
		reflection = Bitmap.createBitmap(src, 0, height / 2, width, height / 2,
				matrix, true);
		// 產生原始圖片與反射圖片合體後的結果圖片Bitmap
		// 這時還是空的
		Bitmap result;
		result = Bitmap.createBitmap(width, height + height / 5,
				Config.ARGB_8888);
		// 使用畫布
		Canvas canvas;
		canvas = new Canvas(result);
		// 將原始圖片寫到結果圖片畫布上
		canvas.drawBitmap(src, 0, 0, null);
		// 將反射圖片寫到結果圖片畫布上
		canvas.drawBitmap(reflection, 0, height + margin, null);

		// 到這裡已經與反射圖片合體完成了
		// 接下來要做淡化處理
		Paint paint = new Paint();
		// 使用LinearGradient這個直線方向的漸層
		LinearGradient shader;
		// 製作漸入透明的漸層
		// 0x90ffffff(稍微透明) -> 0x00FFFFFF(完全透明)
		shader = new LinearGradient(0, height, 0, result.getHeight() + margin,
				0x80ffffff, 0x00ffffff, TileMode.CLAMP);
		// 因為繼承Shader類別，所以使用setShader設定給Paint。
		paint.setShader(shader);
		// 指定顏色轉換模式
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		// 描繪漸層
		canvas.drawRect(0, height, width, result.getHeight(), paint);

		return result;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		db.close();
	}

}
