package com.cwbuyer.code;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.cwbuyer.format.CountryData;
import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;

public class AddCountry extends Activity
{
	private int mMode = 0;
	private int mID = 0;
	CountryData mData = null;
	
	//	0單機 1On_line 2.Off_line
	int of_line=Utilis.toInt(Utilis.getIni(AddCountry.this, "SYS", "IMPORT", 3));
	String mUid=Utilis.getIni(AddCountry.this, "SYS", "IMPORT", 2);  //ex:3g001

	interface Mode{
		int ADD = 0;
		int EDIT = 1;
	}
	
	ImageView OutPhoto = null;
	Uri mImageCaptureUri = null;
	private String mImagePath = null;
	
	public final static String SAVE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ File.separator + "cwbuyer" + File.separator;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		String OutPhotoURI;
		if ((requestCode == 1010) && (resultCode == RESULT_OK)) // 相本
		{
			Uri uri = data.getData();
			{
				if (uri.toString().indexOf("content://") >= 0) {
					OutPhotoURI = Utilis.getRealPathFromURI(AddCountry.this, uri);
				} else {
					OutPhotoURI = uri.getPath();
				}
				Bitmap bitmap = Utilis.getLimitBitmap(
						OutPhotoURI, 320, 480);
				if (bitmap != null) {
					mImagePath = OutPhotoURI;
					mData.icon = mImagePath; 
//					OutPhoto.setScaleType(ScaleType.FIT_XY);
					OutPhoto.setImageBitmap(bitmap);
				}
			}
		}
		if ((requestCode == 1009) && (resultCode == RESULT_OK)) // 照相
		{
			//ContentResolver cr = this.getContentResolver();
			if (data != null) {
				try {
					Bundle extras = data.getExtras();
					if (extras != null) {
						OutPhotoURI = mImageCaptureUri.getPath();
						Bitmap bitmap = Utilis.getLimitBitmap(
								mImageCaptureUri.getPath(), 320, 480);

						if (bitmap != null) {
							mImagePath = OutPhotoURI;
							mData.icon = mImagePath;
//							OutPhoto.setScaleType(ScaleType.FIT_XY);
							OutPhoto.setImageBitmap(bitmap);
						}
					}
				}catch (Exception e){
				}
			} else {
				try {
					OutPhotoURI = mImageCaptureUri.getPath();
					// Bitmap bitmap =
					// Utilis.getSmallPic(mImageCaptureUri.getPath());
					Bitmap bitmap = Utilis.getLimitBitmap(
							mImageCaptureUri.getPath(), 320, 480);
					if (bitmap != null) {
						mImagePath = OutPhotoURI;
						mData.icon = mImagePath;
//						OutPhoto.setScaleType(ScaleType.FIT_XY);
						OutPhoto.setImageBitmap(bitmap);
					}
				} catch (Exception e) {
				}
			}
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_country);
		setTitle("國別資料編輯");
		mID = getIntent().getIntExtra("id", 0);
		mMode = getIntent().getIntExtra("mode", Mode.ADD);
		mData = new CountryData();
		mData.lamin=0.0;mData.lamax=0.0;mData.lomin=0.0;mData.lomax=0.0;
		((EditText)findViewById(R.id.edit_lamin)).setText("" + mData.lamin);
		((EditText)findViewById(R.id.edit_lamax)).setText("" + mData.lamax);
		((EditText)findViewById(R.id.edit_lomin)).setText("" + mData.lomin);
		((EditText)findViewById(R.id.edit_lomax)).setText("" + mData.lomax);
		
		OutPhoto = (ImageView)findViewById(R.id.img_country);
		
		if(mMode == Mode.EDIT){
			getData(mID);
		}else {
			mData.icon = "drawable/country_twn";
			mData.name = "台灣";
			
			((ImageView)findViewById(R.id.img_country)).setImageResource(R.drawable.country_twn);
		}
		
		((Button)findViewById(R.id.btn_save)).setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MenuClick());
		((ImageView)findViewById(R.id.img_country)).setOnClickListener(new MenuClick());
		((EditText)findViewById(R.id.edit_rate)).setOnClickListener(new MenuClick());
		((EditText)findViewById(R.id.edit_lamin)).setOnClickListener(new MenuClick());
		((EditText)findViewById(R.id.edit_lamax)).setOnClickListener(new MenuClick());
		((EditText)findViewById(R.id.edit_lomin)).setOnClickListener(new MenuClick());
		((EditText)findViewById(R.id.edit_lomax)).setOnClickListener(new MenuClick());
		

		//自動彈出鍵盤		
		Timer timer = new Timer();   
        timer.schedule(new TimerTask(){   
            @Override  
            public void run() {   
                InputMethodManager m = (InputMethodManager)AddCountry.this.getSystemService(Context.INPUT_METHOD_SERVICE);   
                m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);   
            }   
               
        }, 200);
	}
	
	class MenuClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			Utilis.runVibrate(AddCountry.this);
			switch(id){
				case R.id.edit_rate:
				case R.id.edit_lamin:
				case R.id.edit_lomin:
				case R.id.edit_lamax:
				case R.id.edit_lomax:
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(((EditText)findViewById(id)).getWindowToken(), 0);
					DialogUtilis.showComputer(AddCountry.this, id);
					break;
				case R.id.btn_save:
					if(saveData() == true)
					{
						finish();
					}
					break;
				case R.id.btn_next:
				{
					if(saveData() == true){
						Intent intent = new Intent();
						intent.setClass(AddCountry.this, AddCountry.class);
						intent.putExtra("mode", Mode.ADD);
						finish();
					}
					break;
				}
				case R.id.btn_exit:
					finish();
					break;
				case R.id.img_country:
				{
					DialogUtilis.showDialog(AddCountry.this, "請選擇圖片的方式", -1,new String[] {"從相機","從檔案"}, new IDialog(){
						public void onDialogFinish(int nPos, String choice) {
							if(nPos == 0){
								eventImgCapture();
							}else{
								eventImgFile();
							}
						}
					});
					break;
				}
			}
			
		}
	}

	// 選擇國家
	@SuppressWarnings("unused")
	private void showChoice() {
		View view = LayoutInflater.from(this).inflate(R.layout.dlg_gridview,
				null, false);
		GridView grid = (GridView)view.findViewById(R.id.grid_select);
		final SelectAdapter adapter = new SelectAdapter(this);
		final AlertDialog dialog = new AlertDialog.Builder(this).setTitle("請選擇國家").setView(view)
		.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		}).create();
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				mData.icon = adapter.getDrawableString(pos);
				mData.name = adapter.getCountryString(pos);
				((EditText)findViewById(R.id.edit_name)).setText(mData.name);
				((ImageView)findViewById(R.id.img_country)).setImageResource(adapter.getDrawableId(pos));
				dialog.dismiss();
			}
		});
		dialog.show();
	}
	
	class SelectAdapter extends BaseAdapter{
		private Integer[] mThumbIds = {
			R.drawable.country_twn,
			R.drawable.country_chi,
			R.drawable.country_koe,
			R.drawable.country_jpn
		};
		
		private String[] mIconPath = {
				"drawable/country_twn",
				"drawable/country_chi",
				"drawable/country_koe",
				"drawable/country_jpn"
		};
		
		private String[] mIconName = {
				"台灣",
				"中國",
				"韓國",
				"日本"
		};
		
		private Context context;
		
		public SelectAdapter(Context cnt){
			context = cnt;
		}
		
		public int getDrawableId(int pos){
			return mThumbIds[pos];
		}
		
		public String getDrawableString(int pos){
			return mIconPath[pos];
		}
		public String getCountryString(int pos){
			return mIconName[pos];
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mThumbIds.length;
		}

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ImageView imageView;
			if (convertView == null) {
				// if it's not recycled, initialize some attributes
				imageView = new ImageView(context);
				imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				imageView.setPadding(8, 8, 8, 8);
			} else {
				imageView = (ImageView) convertView;
			}

			imageView.setImageResource(mThumbIds[position]);
			return imageView;
		}
	}
	
	private boolean saveData(){
		
		boolean succed=true;
		
		String name = DBCloud.chkStr(((EditText)findViewById(R.id.edit_name)).getText().toString());
		String rate = ((EditText)findViewById(R.id.edit_rate)).getText().toString();
		String lamin = ((EditText)findViewById(R.id.edit_lamin)).getText().toString();
		String lamax = ((EditText)findViewById(R.id.edit_lamax)).getText().toString();
		String lomin = ((EditText)findViewById(R.id.edit_lomin)).getText().toString();
		String lomax = ((EditText)findViewById(R.id.edit_lomax)).getText().toString();
		if (lamin.length()==0) lamin="0.0";
		if (lamax.length()==0) lamax="0.0";
		if (lomin.length()==0) lomin="0.0";
		if (lomax.length()==0) lomax="0.0";
		
		if(name == null || name.length() <= 0){
			Toast.makeText(this, "請輸入國家名稱", Toast.LENGTH_SHORT).show();
			return false;
		}
		if(rate == null || rate.length() <= 0 ){
			Toast.makeText(this, "請輸入匯率", Toast.LENGTH_SHORT).show();
			return false;
		}
		
		ContentValues value = new ContentValues();
    	value.put("NAME", name);
    	value.put("PIC", mData.icon);
    	value.put("RATE", rate);
    	value.put("LAMIN", lamin);
    	value.put("LAMAX", lamax);
    	value.put("LOMIN", lomin);
    	value.put("LOMAX", lomax);
    	
		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(name).append(";");
					bfstrF.append("NAME").append(";");
					bfstr.append(mData.icon).append(";");
					bfstrF.append("PIC").append(";");
					bfstr.append(rate).append(";");
					bfstrF.append("RATE").append(";");
					bfstr.append(lamin).append(";");
					bfstrF.append("LAMIN").append(";");
					bfstr.append(lamax).append(";");
					bfstrF.append("LAMAX").append(";");
					bfstr.append(lomin).append(";");
					bfstrF.append("LOMIN").append(";");
					bfstr.append(lomax);
					bfstrF.append("LOMAX");
					
				Toast.makeText(AddCountry.this, "正前往雲端編輯_商品類別中,請稍候....", Toast.LENGTH_SHORT).show();
				Thread t = new Thread(new DBCloud.sendPostRunnableQC(AddCountry.this,bfstr.toString(),bfstrF.toString(),1));
				t.start();
    	}else if(mMode == EMode.ADD){
    		SQLiteDatabase db = Utilis.getDB(this);
	    	long result = db.insert(TbName.QC_COUNTRY, 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_COUNTRY, 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;
	}
	
	private void getData(int id){
		SQLiteDatabase db = Utilis.getDB(this);
		Cursor cursor = db.rawQuery("select * from qc_country where _ID="+id, null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
					mData = new CountryData();
					mData.id = cursor.getInt(cursor.getColumnIndex("_ID"));
					mData.icon = cursor.getString(cursor.getColumnIndex("PIC"));
					mData.name = cursor.getString(cursor.getColumnIndex("NAME"));
					mData.rate = cursor.getDouble(cursor.getColumnIndex("RATE"));
					mData.lamin = cursor.getDouble(cursor.getColumnIndex("LAMIN"));
					mData.lamax = cursor.getDouble(cursor.getColumnIndex("LAMAX"));
					mData.lomin = cursor.getDouble(cursor.getColumnIndex("LOMIN"));
					mData.lomax = cursor.getDouble(cursor.getColumnIndex("LOMAX"));
					// 需要修改
//					((ImageView)findViewById(R.id.img_country)).setImageDrawable(Utilis.getResourceImage(this, mData.icon));
					OutPhoto.setImageDrawable(Utilis.getResourceImage(this, mData.icon));
					((EditText)findViewById(R.id.edit_name)).setText(mData.name);
					((EditText)findViewById(R.id.edit_rate)).setText("" + mData.rate);
					((EditText)findViewById(R.id.edit_lamin)).setText("" + mData.lamin);
					((EditText)findViewById(R.id.edit_lamax)).setText("" + mData.lamax);
					((EditText)findViewById(R.id.edit_lomin)).setText("" + mData.lomin);
					((EditText)findViewById(R.id.edit_lomax)).setText("" + mData.lomax);
				}
			}catch(Exception e){
				
			}finally{
				cursor.close();
				cursor = null;
			}
		}
		db.close();
		db = null;
	}
	
    private void eventImgCapture() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// Wysie_Soh: Create path for temp file
		File folder = new File( SAVE_FOLDER + ".Country");
		if(folder.exists() == false){
			folder.mkdirs();
		}
		File file = new File(SAVE_FOLDER + ".Country",
				"cwbuyer_" + String.valueOf(System.currentTimeMillis())
						+ ".jpg");
		
		if(file.exists() == false){
			try{
				file.createNewFile();
			}catch(Exception e){
				
			}
		}
		mImageCaptureUri = Uri.fromFile(file);

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				mImageCaptureUri);

		try {
			intent.putExtra("return-data", true);
			startActivityForResult(intent, 1009);
		} catch (ActivityNotFoundException e) {
			// Do nothing for now
		} catch (Exception e){
		}
	}
	
	private void eventImgFile(){
        Intent intent = new Intent(); 
        /* 開啟Pictures畫面Type設定為image */
        intent.setType("image/*"); 
//        intent.setType("image/*.jpg");
        /* 使用Intent.ACTION_GET_CONTENT這個Action */	     	        
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        /* 取得相片後返回本畫面 */ 
        startActivityForResult(intent, 1010);
	}

}
