package com.cwbuyer.code;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

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

public class AddMacc extends Activity{

	private int CAPTURE = 1010;
	private final int TPICTURE = 1009;
	private static int nPicDegree =0;
	private int mMode = 0;
	private int mID = 0;
	private int rotationInDegrees=0;
	String edpic="";
	AccData mData = null;
	
	//	0單機 1On_line 2.Off_line
	int of_line=Utilis.toInt(Utilis.getIni(AddMacc.this, "SYS", "IMPORT", 3));
	String mUid=Utilis.getIni(AddMacc.this, "SYS", "IMPORT", 2);  //ex:3g001
	
	ImageView OutPhoto = null;
	Uri mImageCaptureUri = null;
	private String mImagePath = null;
	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR", 8);
	public final  String SAVE_FOLDER = filepath + File.separator;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		String OutPhotoURI;
		super.onActivityResult(requestCode, resultCode, data);
		if ((requestCode == CAPTURE) && (resultCode == RESULT_OK)) // 相本
		{
 	    		edpic=filepath +File.separator+"Macc_"+ String.valueOf(DateUtil.getSystemTime())+ ".jpg";
	    		
	    		Bitmap mBitmap=null;Bitmap bitmap=null;
	            Uri selectedImageUri = data.getData();
	            
	            if (Build.VERSION.SDK_INT < 19) {
	            	OutPhotoURI = getPath(selectedImageUri);
	            	mBitmap = Utilis.getScaleBitmap(OutPhotoURI, 210, 280);
					try {
						ExifInterface exif = new ExifInterface(OutPhotoURI);
						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
						rotationInDegrees = exifToDegrees(rotation);
						Matrix matrix = new Matrix();
						matrix.preRotate(rotationInDegrees);
						bitmap = Bitmap.createBitmap(mBitmap, 0, 0, 210, 280, matrix, true);
						
	    		        FileOutputStream fos = null;
	    				try {
	    						fos = new FileOutputStream(edpic);
	   	    					bitmap.compress(CompressFormat.JPEG, 100, fos);
	   	    					fos.close();
	   	    					mBitmap=bitmap;	
	    				} catch (FileNotFoundException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	            else
	            {
	                ParcelFileDescriptor parcelFileDescriptor;
	                try {
	                    parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
	                    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
	                    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
	                    parcelFileDescriptor.close();

	    				ByteArrayOutputStream stream = new ByteArrayOutputStream();
	    				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件
	    		        FileOutputStream fos = null;
	    				try {
	    						fos = new FileOutputStream(edpic);
	    				} catch (FileNotFoundException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	    				try {
	    					bitmap.compress(CompressFormat.JPEG, 100, fos);
	    					fos.close();
	    					mBitmap = Utilis.getScaleBitmap(edpic, 210, 280);
	    					
	    					try {
	    						ExifInterface exif = new ExifInterface(edpic);
	    						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
	    						rotationInDegrees = exifToDegrees(rotation);
	    						Matrix matrix = new Matrix();
	    						matrix.preRotate(rotationInDegrees);
	    						bitmap = Bitmap.createBitmap(mBitmap, 0, 0, 210, 280, matrix, true);

	    						try {
	    	    						fos = new FileOutputStream(edpic);
	    	   	    					bitmap.compress(CompressFormat.JPEG, 100, fos);
	    	   	    					fos.close();
	    	   	    					mBitmap=bitmap;	
	    	    				} catch (FileNotFoundException e) {
	    	    					// TODO Auto-generated catch block
	    	    					e.printStackTrace();
	    	    				}

	    					} catch (IOException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					}
	    					
	    					
	    				} catch (IOException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	                    
	                } catch (FileNotFoundException e) {
	                    e.printStackTrace();
	                } catch (IOException e) {

	                    e.printStackTrace();
	                }
	            }
				if (mBitmap!=null && mBitmap.getHeight()>0 )
				{
					mImagePath = edpic;
					OutPhoto.setImageBitmap(mBitmap);
				}
		}else if ((requestCode == TPICTURE) && (resultCode == RESULT_OK)) // 照相
		{
			if (data != null) {
				try {
					Bundle extras = data.getExtras();
					if (extras != null) {
						OutPhotoURI = mImageCaptureUri.getPath();
						Bitmap bitmap=null;
						OutPhotoURI = mImageCaptureUri.getPath();
						bitmap = Utilis.getLimitBitmap(
						mImageCaptureUri.getPath(), 80,80);
						if (bitmap != null) {
							ExifInterface exif = new ExifInterface(OutPhotoURI);
							int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
							int rotationInDegrees = exifToDegrees(rotation);
							Matrix matrix = new Matrix();
							matrix.preRotate(rotationInDegrees);
							Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, 80, 80, matrix, true);
							mImagePath = OutPhotoURI;
							//OutPhoto.setScaleType(ScaleType.FIT_XY);
							OutPhoto.setImageBitmap(adjustedBitmap);
						}
					}
				} catch (Exception e) {

				}
			} else {
				try {
					OutPhotoURI = mImageCaptureUri.getPath();
					Bitmap bitmap = Utilis
							.getLimitBitmap(OutPhotoURI, 80, 80);
					if (bitmap != null) {
						Matrix matrix = new Matrix();
						ExifInterface exif = new ExifInterface(OutPhotoURI);
						int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
						int rotationInDegrees = exifToDegrees(rotation);
						
						matrix.preRotate(rotationInDegrees);
						Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
							mImagePath = OutPhotoURI;
							//OutPhoto.setScaleType(ScaleType.FIT_XY);
							OutPhoto.setImageBitmap(adjustedBitmap);
						ByteArrayOutputStream stream = new ByteArrayOutputStream();
						adjustedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);// (0 - 100)压缩文件

				        FileOutputStream fos = null;
						try {
								fos = new FileOutputStream(mImagePath);
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						try {
							adjustedBitmap.compress(CompressFormat.JPEG, 100, fos);
							fos.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
				}
				
				try {
					OutPhotoURI = mImageCaptureUri.getPath();
					Bitmap bitmap = Utilis.getLimitBitmap(
							mImageCaptureUri.getPath(), 80, 80);
					if (bitmap != null) {
						mImagePath = OutPhotoURI;
						OutPhoto.setImageBitmap(bitmap);
					}
				} catch (Exception e) {
				}
			}
		}
	}
	
	private static int exifToDegrees(int exifOrientation) {        
	    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {  return 180; } 
	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {  return 270; }            
	    return nPicDegree;    
	 }

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_macc);
		setTitle("常用收入支出科目編輯");
		
		mID = getIntent().getIntExtra("id", 0);
		mMode = getIntent().getIntExtra("mode", EMode.ADD);
		nPicDegree =Utilis.toInt(Utilis.getIni(this, "SYS", "BACKOUT", 8)); // 帳戶		
		
		OutPhoto = (ImageView)findViewById(R.id.img_acc);
		InputFilter[] FilterArray = new InputFilter[1];
    	FilterArray[0] = new InputFilter.LengthFilter(4);
    	((EditText)findViewById(R.id.edit_accno)).setFilters(FilterArray);
		if(mMode == EMode.ADD){
			mData = new AccData();
			
		}else{
			getData(mID);
			if(mData != null){
				OutPhoto.setImageDrawable(Utilis.getResourceImage(this, mData.icon));
				((EditText)findViewById(R.id.edit_accno)).setText(mData.acc_nom);
				((EditText)findViewById(R.id.edit_accname)).setText("" + mData.acc_txt);
				mImagePath = mData.icon;
			}
		}
		
		OutPhoto.setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_save)).setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_next)).setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MenuClick());
		
	}
	
	class MenuClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			Utilis.runVibrate(AddMacc.this);
			switch(id){
				case R.id.img_acc:
				{
					DialogUtilis.showDialog(AddMacc.this, "請選擇以下功能", -1, new String[]{"拍照","相本"}, new IDialog(){
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch(pos){
								case 0: // 拍照
									eventImgCapture();
									break;
								case 1: // 相本
									eventImgFile();
									break;
							}
						}
					});
					break;
				}
				case R.id.btn_next:
				{
					if(saveData() == true){
						mMode = EMode.ADD;
						mID=0; //複製一筆資料
						Toast.makeText(AddMacc.this, "下一筆資料記錄開始", Toast.LENGTH_SHORT).show();
					}
					break;
				}
				case R.id.btn_save:
					if(saveData() == true){
						finish();
					}
					break;
				case R.id.btn_exit:
					finish();
					break;
			}
		}
	}
	
	public String getPath(Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        @SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return uri.getPath();
}

	
	private boolean saveData(){
		String accno = DBCloud.chkStr(((EditText)findViewById(R.id.edit_accno)).getText().toString().trim());
		String accname = DBCloud.chkStr(((EditText)findViewById(R.id.edit_accname)).getText().toString());
		boolean succed=true;
		SQLiteDatabase db = Utilis.getDB(this);
		
		if((accno == null || accno.length() <= 0) || Utilis.toInt(accno)==0){
			Toast.makeText(this, "請輸入收支代號0001-9999", Toast.LENGTH_SHORT).show();
			db.close();
			return false;
		}
		if(mMode ==EMode.EDIT){
			if( !accno.equalsIgnoreCase(mData.acc_nom)){
				Cursor cs=db.rawQuery("Select * from qc_macc where QNOM like '%" + accno + "%' limit 1", null);
				if (cs.getCount()>0){
					Toast.makeText(this, "收支代碼不可重複!!", Toast.LENGTH_SHORT).show();
					db.close();
					cs.close();
					return false;
				}
				cs.close();
			}
		}	
		
		if(accname == null || accname.length() <= 0 ){
			Toast.makeText(this, "請輸入科目內容", Toast.LENGTH_SHORT).show();
			db.close();
			return false;
		}
		
        if (mImagePath==null || mImagePath.length()<=0){
        	mImagePath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/para/img_additem.png";
		}
		
		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(mID).append(";");
					bfstrF.append("ID").append(";");
					bfstr.append(accno).append(";");
					bfstrF.append("QNOM").append(";");
					bfstr.append(accname).append(";");
					bfstrF.append("TXT").append(";");
					bfstr.append("0").append(";");
					bfstrF.append("IOKEY").append(";");
					bfstr.append(mImagePath);
					bfstrF.append("PIC");
				Toast.makeText(AddMacc.this, "正前往雲端編輯_收支代碼中,請稍候....", Toast.LENGTH_SHORT).show();
				Thread t = new Thread(new DBCloud.sendPostRunnableQC(AddMacc.this,bfstr.toString(),bfstrF.toString(),8));
				t.start();
		}else{
			ContentValues value = new ContentValues();
	    	value.put("QNOM", accno);
	    	value.put("TXT", accname);
	    	value.put("IOKEY", "0");
	    	value.put("PIC", Utilis.makeSPics(this,mImagePath));
			
    		if(mMode == EMode.ADD){
		    	long result = db.insert(TbName.QC_MACC, null, value);
		    	if(result > 0){
		    		Toast.makeText(this, "存取資料成功", Toast.LENGTH_SHORT).show();
		    	}else{
		    		Toast.makeText(this, "存取資料失敗", Toast.LENGTH_SHORT).show();
		    		succed =false;
		    	}
	    	}else{  // EDIT
	    		String[] args = {String.valueOf(mID)};
				int success = db.update(TbName.QC_MACC, value,
						"_ID=?", args);
				if(success > 0){
					Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
		    		succed =false;
				}
	    	}
    		value.clear();
    	}	
		db.close();
		return succed;
	}

	public void getData(int id){
		SQLiteDatabase db = Utilis.getDB(this);
		Cursor cursor = db.rawQuery("select * from "+TbName.QC_MACC+" where _ID="+id, null);
		if(cursor != null){
			try{
				if(cursor.getCount() > 0){
					cursor.moveToFirst();
						mData = new AccData();
						mData.id = cursor.getInt(cursor.getColumnIndex("_ID"));
						mData.icon = cursor.getString(cursor.getColumnIndex("PIC"));
						mData.acc_nom = cursor.getString(cursor.getColumnIndex("QNOM"));
						mData.acc_txt = cursor.getString(cursor.getColumnIndex("TXT"));
						mData.acc_iokey = cursor.getString(cursor.getColumnIndex("IOKEY"));
					}
			}catch(Exception e){
				e.printStackTrace();
			}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 );
		if(folder.exists() == false){
			folder.mkdirs();
		}
		File file = new File(SAVE_FOLDER ,"Macc_" + 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, TPICTURE);
		} catch (ActivityNotFoundException e) {
			// Do nothing for now
		} catch (Exception e){
		}
	}
	
    // 相本
	private void eventImgFile(){
        Intent intent = new Intent(); 
        intent.setType("image/*"); 
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        startActivityForResult(Intent.createChooser(intent,"Select Picture"),CAPTURE);
	}
	
}
