package com.cwbuyer.code;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.cwbuyer.format.EMode;
import com.cwbuyer.lib.ColorPickerDialog;
import com.cwbuyer.lib.ColorPickerDialog.OnColorChangedListener;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;

@SuppressLint("DefaultLocale")
public class AddColor  extends Activity{
	
	private int mMode = 0;
	private int mID = 0;
	private int mColor = 0;
	private String hexColor="0XFFC7C7C7";

	//	0單機 1On_line 2.Off_line
	int of_line=Utilis.toInt(Utilis.getIni(AddColor.this, "SYS", "IMPORT", 3));
	String mUid=Utilis.getIni(AddColor.this, "SYS", "IMPORT", 2);  //ex:3g001
	
	private String mColorNumber = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_color);
		setTitle("產品顏色編輯");
		mID = getIntent().getIntExtra("id", 0);
		mColor = getIntent().getIntExtra("color", Color.rgb(255, 0, 0));
		mMode = getIntent().getIntExtra("mode", EMode.ADD);
		String name = getIntent().getStringExtra("color_name");
		String number = getIntent().getStringExtra("color_number");
		((ImageView)findViewById(R.id.img_color)).setBackgroundColor(mColor);
		((ImageView)findViewById(R.id.img_color)).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(AddColor.this);
				ColorPickerDialog dialog = new ColorPickerDialog(AddColor.this, new OnColorChangedListener(){
					@Override
					public void colorChanged(int color) {
						// TODO Auto-generated method stub
						((ImageView)findViewById(R.id.img_color)).setBackgroundColor(color);
						mColor = color;
						hexColor = "0X" + Integer.toHexString(mColor).toUpperCase();						
					}
				}, mColor);
				dialog.show();
			}
		});
		// 限制最多只能三個字
		InputFilter[] FilterArray = new InputFilter[1];
    	FilterArray[0] = new InputFilter.LengthFilter(2);
		InputFilter[] FilterArray1 = new InputFilter[1];
    	FilterArray1[0] = new InputFilter.LengthFilter(6);
    	((EditText)findViewById(R.id.edit_name)).setFilters(FilterArray1);
    	((EditText)findViewById(R.id.edit_number)).setFilters(FilterArray);
    	
		if(name != null && name.length() > 0){
			((EditText)findViewById(R.id.edit_name)).setText(name);
		}
		
		if(number != null && number.length() > 0){
			mColorNumber = number;
			((EditText)findViewById(R.id.edit_number)).setText(number);
		}
		
		((Button)findViewById(R.id.btn_save)).setOnClickListener(new MenuClick());
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MenuClick());
        ((Button)findViewById(R.id.btn_save)).setOnLongClickListener(new MainLongClick());
		
	}
	
	class MenuClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			Utilis.runVibrate(AddColor.this);
			switch(id){
			case R.id.btn_save:
				if(saveData() == true){
					finish();
				}
				break;
			case R.id.btn_exit:
				finish();
				break;
			}
		}
	}


	class MainLongClick implements OnLongClickListener { //所有長按的觸發事件,在此集中管理
	@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
			int id = v.getId();
			Utilis.runVibrate(AddColor.this);
			switch (id) {
			case R.id.btn_save:  //將所有顏色10進位轉為16進位
			  {
					SQLiteDatabase db = Utilis.getDB(AddColor.this);
						try{
							Cursor cursor = db.rawQuery("Select * from qc_color", null); 
							if(cursor != null){
								if(cursor.getCount() > 0){
									while (cursor.moveToNext()){
										if (cursor.getString(cursor.getColumnIndex("PIC")).indexOf("0X")<0){
											String Cno=cursor.getString(cursor.getColumnIndex("NO"));
											mColor=cursor.getInt(cursor.getColumnIndex("PIC"));
											hexColor = "0X" + Integer.toHexString(mColor).toUpperCase();
											ContentValues value = new ContentValues();
									    	value.put("PIC", hexColor);
								    		String[] args = {String.valueOf(Cno)};
											@SuppressWarnings("unused")
											int success = db.update(com.cwbuyer.lib.TbName.QC_COLOR, value,"NO=?", args);
										}
									}
									Toast.makeText(AddColor.this, "修改資料成功", Toast.LENGTH_SHORT).show();
								}
								cursor.close();
							}
						}catch(Exception e){
							e.printStackTrace();
						}
					db.close();
				  
			  }	
			}
			return true;
		}
	}
	
	private boolean saveData(){
		String name = DBCloud.chkStr(((EditText)findViewById(R.id.edit_name)).getText().toString());
		String number = DBCloud.chkStr(((EditText)findViewById(R.id.edit_number)).getText().toString());
		boolean succed=true;
		
		if(name == null || name.length() <= 0){
			Toast.makeText(this, "請輸入顏色名稱", Toast.LENGTH_SHORT).show();
			return false;
		}
		if(number == null || number.length() <= 0 ){
			Toast.makeText(this, "請輸入顏色代碼", Toast.LENGTH_SHORT).show();
			return false;
		}
		// 需判斷顏色代碼是否有重覆
		if(mMode ==EMode.EDIT){
			if(number.equalsIgnoreCase(mColorNumber) == false){
				if(isColorUsed(number) == true){
					Toast.makeText(this, "此顏色代碼已經使用", Toast.LENGTH_SHORT).show();
					return false;
				}
			}
		}else{
			if(isColorUsed(number) == true){
				Toast.makeText(this, "此顏色代碼已經使用", Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		
		ContentValues value = new ContentValues();
    	value.put("TXT", name);
    	value.put("NO", number);
    	value.put("PIC", hexColor);
		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(number).append(";");
					bfstrF.append("NO").append(";");
					bfstr.append(name).append(";");
					bfstrF.append("TXT").append(";");
					bfstr.append(hexColor);
					bfstrF.append("PIC");
				Toast.makeText(AddColor.this, "正前往雲端編輯中,請稍候....", Toast.LENGTH_SHORT).show();
				Thread t = new Thread(new DBCloud.sendPostRunnableQC(AddColor.this,bfstr.toString(),bfstrF.toString(),3));
				t.start();
    	}else if(mMode == EMode.ADD){
    		SQLiteDatabase db = Utilis.getDB(this);
	    	long result = db.insert(TbName.QC_COLOR, 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_COLOR, 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 boolean isColorUsed(String number){
		boolean bResult = false;
		SQLiteDatabase db = Utilis.getDB(this);
		if(db != null){
			try{
				Cursor cursor = db.rawQuery("Select * from qc_color where NO like '%" + number + "%' limit 1", null); 
				if(cursor != null){
					if(cursor.getCount() > 0){
						bResult = true;
					}
					cursor.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}else{
			bResult = true;
		}
		db.close();
		return bResult;
	}
}
