package com.cwbuyer.code;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
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.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.cwbuyer.adapter.WashAdapter;
import com.cwbuyer.adapter.WashAdapter.WashData;
import com.cwbuyer.format.EMode;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.ReadFileUtilx;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;

// 洗滌組合
public class AddWash extends Activity{
	
	private int mMode = 0;
	private int mID = 0;
	private WashData mData = null;
	
	//	0單機 1On_line 2.Off_line
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	String mUid=Utilis.getIni(this, "SYS", "IMPORT", 2);  //ex:3g001
	
	private List<String> ImageList;
	private ListView mListView;
	
	private CWashAdapter mAdapter = null;
	
	private HashMap<Integer, Boolean>  mUserChoice = new HashMap<Integer, Boolean>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_wash);
		setTitle("洗滌組合編輯");
		
		
		String sdcard = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
		ImageList = ReadFileUtilx.getImagesFromSDx(sdcard + "/cwbuyer/wash/");
		//初始資料
		for(int i = 0; i < ImageList.size(); i++){
			mUserChoice.put(i, false);
		}
		
		mID = getIntent().getIntExtra("id", 0);
		mMode = getIntent().getIntExtra("mode", 0);
		if(mMode == EMode.EDIT && mID != 0){
			getData(this);
			// set mUserChoice
			if(mData != null){
				setUserChoice();
			}
		}else{
			mData = new WashData(); 
		}
		
		mAdapter = new CWashAdapter(this);
		mListView = (ListView)findViewById(R.id.listview);
		mListView.setAdapter(mAdapter);
		
		((Button)findViewById(R.id.btn_save)).setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MenuClick());
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		
		
		try{
			mAdapter.release();
			mAdapter = null;
			
			if(ImageList != null){
				ImageList.clear();
				ImageList = null;
			}
			
			mListView = null;
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	class MenuClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			Utilis.runVibrate(AddWash.this);
			switch(id){
			case R.id.btn_save:
				if(saveData() == true){
					finish();
				}
				break;
			case R.id.btn_exit:
				finish();
				break;
			}
		}
	}
	
	@SuppressWarnings("unused")
	private int getIndex(String drawname){
		int index = 0;
		if(drawname.indexOf("img_wash_1") >= 0){
			index = 0;
		}else if(drawname.indexOf("img_wash_2") >= 0){
			index = 1;
		}else if(drawname.indexOf("img_wash_3") >= 0){
			index = 2;
		}else if(drawname.indexOf("img_wash_4") >= 0){
			index = 3;
		}else if(drawname.indexOf("img_wash_5") >= 0){
			index = 4;
		}else if(drawname.indexOf("img_wash_6") >= 0){
			index = 5;
		}
		return index;
	}
	
	public void getData(Context context){
		SQLiteDatabase db = Utilis.getDB(context);
		if(db != null){
			Cursor cursor = db.rawQuery("select * from qc_wash where _id=" + mID, null);
			if(cursor != null){
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						mData = new WashAdapter.WashData();
						mData.id = cursor.getInt(cursor.getColumnIndex("_ID"));
							String strImage1 = null;
							strImage1 = cursor.getString(cursor.getColumnIndex("WASH10"));
							if(strImage1 != null && strImage1.length() > 0){
								mData.mPics.add(strImage1);
							}
							strImage1 = cursor.getString(cursor.getColumnIndex("WASH20"));
							if(strImage1 != null && strImage1.length() > 0){
								mData.mPics.add(strImage1);
							}
							strImage1 = cursor.getString(cursor.getColumnIndex("WASH30"));
							if(strImage1 != null && strImage1.length() > 0){
								mData.mPics.add(strImage1);
							}
							strImage1 = cursor.getString(cursor.getColumnIndex("WASH40"));
							if(strImage1 != null && strImage1.length() > 0){
								mData.mPics.add(strImage1);
							}
							strImage1 = cursor.getString(cursor.getColumnIndex("WASH50"));
							if(strImage1 != null && strImage1.length() > 0){
								mData.mPics.add(strImage1);
							}
							strImage1 = cursor.getString(cursor.getColumnIndex("WASH60"));
							if(strImage1 != null && strImage1.length() > 0){
								mData.mPics.add(strImage1);
							}
					}
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					cursor.close();
					cursor = null;
				}
			}
			db.close();
			db = null;
		}
	}
	
	private ArrayList<Integer> getUserChoice(){
		ArrayList<Integer> listIndex = new ArrayList<Integer>();
		for(int i = 0; i < mUserChoice.size(); i ++){
			if(mUserChoice.get(i) == true){
				listIndex.add(i);
			}
		}
		return listIndex;
	}
	
	private void setUserChoice(){
		for(int i = 0; i < mData.mPics.size(); i++){
			boolean bFind = false;
			for(int x = 0; x < ImageList.size() && bFind == false; x++){
				if(mData.mPics.get(i).equalsIgnoreCase(ImageList.get(x))){
					if(mUserChoice.containsKey(x)){
						mUserChoice.remove(x);
					}
					mUserChoice.put(x, true);
					bFind = true;
				}
			}
		}
	}
	
	@SuppressWarnings("unused")
	private int getUserChoiceCount(){
		int count = 0;
		for(int i = 0; i < mUserChoice.size(); i ++){
			if(mUserChoice.get(i) == true){
				count++;
			}
		}
		return count;
	}
	
	private boolean saveData(){
		boolean succed=true;
		
		ArrayList<Integer> listIndex = getUserChoice();
		if(listIndex.size() <= 0){
			Toast.makeText(AddWash.this, "至少選擇一張圖片", Toast.LENGTH_SHORT).show();
			return false;
		}else if(listIndex.size() > 6){
			Toast.makeText(AddWash.this, "最多只能選擇六張圖片", Toast.LENGTH_SHORT).show();
			return false;
		}
		
		ContentValues value = new ContentValues();
    	String[] dbName = new String[]{"WASH10","WASH20","WASH30","WASH40","WASH50","WASH60"};

    	for(int i = 0; i < 6; i ++){
    		if(i < listIndex.size()){
    			value.put(dbName[i], ImageList.get(listIndex.get(i)));
    		}else{
    			value.put(dbName[i], "");
    		}
    	}
		if (Utilis.haveInternet(this) && of_line!=0){  //有網路的狀態且非單機,優先雲端運算,再行Hander維護Client端
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
					bfstr.append(mUid).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(mID).append(";");
					bfstrF.append("_ID").append(";");
 					bfstr.append(ImageList.get(listIndex.get(0))).append(";");
					bfstrF.append("WASH10").append(";");
 					bfstr.append("x").append(";");
					bfstrF.append("WASH11").append(";");
 					bfstr.append((ImageList.get(listIndex.get(1)))).append(";");
					bfstrF.append("WASH20").append(";");
 					bfstr.append("x").append(";");
					bfstrF.append("WASH21").append(";");
 					bfstr.append((ImageList.get(listIndex.get(2)))).append(";");
					bfstrF.append("WASH30").append(";");
 					bfstr.append("x").append(";");
					bfstrF.append("WASH31").append(";");
 					bfstr.append((ImageList.get(listIndex.get(3)))).append(";");
					bfstrF.append("WASH40").append(";");
 					bfstr.append("x").append(";");
					bfstrF.append("WASH41").append(";");
 					bfstr.append((ImageList.get(listIndex.get(4)))).append(";");
					bfstrF.append("WASH50").append(";");
 					bfstr.append("x").append(";");
					bfstrF.append("WASH51").append(";");
 					bfstr.append((ImageList.get(listIndex.get(5)))).append(";");
					bfstrF.append("WASH60").append(";");
 					bfstr.append("x");
					bfstrF.append("WASH61");
					Toast.makeText(this, "正前往雲端編輯_商品類別中,請稍候....", Toast.LENGTH_SHORT).show();
					Thread t = new Thread(new DBCloud.sendPostRunnableQC(this,bfstr.toString(),bfstrF.toString(),7));
					t.start();
    	}else if(mMode == EMode.ADD){
    		SQLiteDatabase db = Utilis.getDB(this);
	    	long result = db.insert(TbName.QC_WASH, null, value);
	    	if(result > 0){
	    		Toast.makeText(this, "存取資料成功", Toast.LENGTH_SHORT).show();
	    	}else{
	    		Toast.makeText(this, "存取資料失敗", Toast.LENGTH_SHORT).show();
	    		succed =false;
	    	}
	    	db.close();
    	}else{  // EDIT
    		SQLiteDatabase db = Utilis.getDB(this);
    		String[] args = {String.valueOf(mID)};
			int success = db.update(com.cwbuyer.lib.TbName.QC_WASH, value,
					"_ID=?", args);
			if(success > 0){
				Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
	    		succed =false;
			}
			db.close();
    	}
		value.clear();
		return succed;
	}
	
	public class CWashAdapter extends BaseAdapter{
		private LayoutInflater mInflater;
		public CWashAdapter(Context context){
			   mInflater = LayoutInflater.from(context);
		}
		
		public void release(){
			mInflater = null;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return ImageList.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;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_wash, null);
				holder = new ViewHolder();
				holder.icon = (ImageView) convertView.findViewById(R.id.image);
				holder.ckb = (CheckBox) convertView.findViewById(R.id.chkbox);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			holder.ckb.setOnCheckedChangeListener(new CheckState(position));
			
			boolean bCheck = mUserChoice.get(position);
			holder.ckb.setChecked(bCheck);
			try{
				Bitmap bmp = Utilis.getLimitBitmap(ImageList.get(position), 200, 45);  
				holder.icon.setImageBitmap(bmp);
			}catch(Exception e){
				e.printStackTrace();
			}
			
			return convertView;
		}
		
		protected class CheckState implements OnCheckedChangeListener{
			
			private int mPos = 0;
			
			public CheckState(int pos){
				mPos = pos;
			}
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if(mUserChoice.containsKey(mPos)){
					mUserChoice.remove(mPos);
				}
				mUserChoice.put(mPos, isChecked);
			}
		}
		
		/* class ViewHolder */
		private class ViewHolder {
			CheckBox ckb;
			ImageView icon;
		}
	}
}
