package com.cwbuyer.main;

import java.util.LinkedList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.adapter.AccountAdapter;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.KeySet;
import com.cwbuyer.lib.AccountUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;


// 帳戶管理
public class ManageAccount extends Activity{
	
	LinkedList<AccountData> mList = new LinkedList<AccountData>();
	TextView mTextTotal = null;
	AccountAdapter mAdapter = null;
	// 帳戶資料
	public static class AccountData{
		public String strText;
		public String strRate;
		public String strNote;
		public int nID;
		public int nMoney;
		public int nSort;
		public int nPic;
		public int nInit;
		public String strShowInfo;
	}
	
	public void onCreate(Bundle bundle){
		super.onCreate(bundle);
		setContentView(R.layout.manage_account_layout);
		
		mTextTotal = (TextView)findViewById(R.id.text_duration);
		
		mAdapter = new AccountAdapter(this);
		ListView listview = (ListView)findViewById(R.id.list_account);
		listview.setAdapter(mAdapter);
		
		listview.setOnItemLongClickListener(mOnLongItemClick);
		listview.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				AccountData data = mList.get(position);
				Intent intent = new Intent();
				intent.setClass(ManageAccount.this, ManageItem.class);
				intent.putExtra("accountid", data.nID);
				intent.putExtra("search_mode", KeySet.SearchMode.ACCOUNT);
				startActivity(intent);
			}
		});
		
		((Button)findViewById(R.id.btn_new)).setOnClickListener(mMainClcik);
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(mMainClcik);
	}
	
	public void onResume(){
		super.onResume();
		getAccountData();
	}
	
	private void getAccountData(){
		if(mList != null){
			mList.clear();
		}
		SQLiteDatabase db = Utilis.getDB(this);
		try{
			Cursor cursor = db.rawQuery("select * from " + TbName.ACCOUNT + " order by accsort DESC", null);
			if(cursor != null){
				try{
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						for(int i = 0; i < cursor.getCount(); i++){
							AccountData data = new AccountData();
							data.nID =  cursor.getInt(cursor.getColumnIndex("_id"));
							data.strText =  cursor.getString(cursor.getColumnIndex("acctext"));
							data.strRate =  cursor.getString(cursor.getColumnIndex("accrate"));
							data.strNote =  cursor.getString(cursor.getColumnIndex("accnote"));
							data.nMoney =  cursor.getInt(cursor.getColumnIndex("accmoney"));
							data.nSort =  cursor.getInt(cursor.getColumnIndex("accsort"));
							data.nPic =  cursor.getInt(cursor.getColumnIndex("accpic"));
							data.nInit =  cursor.getInt(cursor.getColumnIndex("accinit"));
							mList.add(data);
							cursor.moveToNext();
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					cursor.close();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		// 設定總分數
		countTotal();
		mAdapter.setData(mList);
		mAdapter.notifyDataSetChanged();
	}
	
	private void countTotal(){
		int total = 0;
		for(int i = 0; i < mList.size(); i++){
			AccountData data = mList.get(i);
			total += (int)((double)data.nMoney * (double)Utilis.toDouble(data.strRate));  
		}
		mTextTotal.setText("總共: " + total);
	}
	
	private void deleteAccount(int pos){
		int id = mList.get(pos).nID;
		SQLiteDatabase db = Utilis.getDB(this);
		try{
			db.execSQL("delete from account where _id=" + id);
			mList.remove(pos);
			mAdapter.notifyDataSetChanged();
			Toast.makeText(this, "刪除帳號成功", Toast.LENGTH_SHORT).show();
		}catch(Exception e){
			Toast.makeText(this, "刪除資料失敗", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		if(db != null){
			db.close();
		}
	}
	
	private OnItemLongClickListener mOnLongItemClick = new OnItemLongClickListener(){
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				final int position, long arg3) {
			Utilis.runVibrate(ManageAccount.this);
			DialogUtilis.showDialog(ManageAccount.this, "請選擇以下功能", -1, new String[]{"設定初始金額","設定帳號排序數字","重新計算餘額","編輯帳戶資料","刪除帳號",}, new IDialog(){
				@Override
				public void onDialogFinish(int pos, String choice) {
					switch(pos){
						case 0: // 設定初始值
							final int oldInit = mList.get(position).nInit;
							final int accountId = mList.get(position).nID; 
							DialogUtilis.showComputer(ManageAccount.this, new IDialog(){
								@Override
								public void onDialogFinish(int pos, String choice) {
									
									int number = Utilis.toInt(choice);
									SQLiteDatabase db = Utilis.getDB(ManageAccount.this);
									try{
										ContentValues value = new ContentValues();
										value.put("accinit", number);
											int success = db.update(com.cwbuyer.lib.TbName.ACCOUNT, value,
													"_id=?", new String[]{"" + mList.get(position).nID});
											if(success > 0){
												Toast.makeText(ManageAccount.this, "修改資料成功", Toast.LENGTH_SHORT).show();
												AccountUtil.updateValue(ManageAccount.this, db,accountId,accountId, oldInit, number);
												getAccountData();
											}else{
												Toast.makeText(ManageAccount.this, "修改資料失敗", Toast.LENGTH_SHORT).show();
											}
									}catch(Exception e){
										e.printStackTrace();
									}
									if(db != null){
										db.close();
									}
								}
							});
							break;
					case 1: // 設定排序
						showSortDialog(mList.get(position).nID, mList.get(position).nSort);
						break;
					case 2: // 重新整理
						break;
					case 3:
						showNewDialog(mList.get(position),true);
						break;
					case 4:
						deleteAccount(position);
						break;
					}
				}
			});
			return false;
		}
	};
	
	private void insertAccount(AccountData data, boolean bEdit){
		boolean bResult = false;
		SQLiteDatabase db = Utilis.getDB(this);
		try{
			ContentValues value = new ContentValues();
			value.put("acctext", data.strText);
			value.put("accrate", data.strRate);
			value.put("accnote", data.strNote);
			value.put("accpic", data.nPic);
			if(bEdit == false){
				long result = db.insert(TbName.ACCOUNT, null, value);
				if (result > 0) {
					 Toast.makeText(this, "新增帳號成功", Toast.LENGTH_SHORT).show();
					bResult = true;
				} else {
					Toast.makeText(this, "存取帳號失敗", Toast.LENGTH_SHORT).show();
				}
			}else{
				int success = db.update(com.cwbuyer.lib.TbName.ACCOUNT, value,
						"_id=?", new String[]{"" + data.nID});
				if(success > 0){
					Toast.makeText(this, "修改帳號成功", Toast.LENGTH_SHORT).show();
					bResult = true;
				}else{
					Toast.makeText(this, "修改帳號失敗", Toast.LENGTH_SHORT).show();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		if(db != null){
			db.close();
		}
		
		if(bResult == true){
			getAccountData();
		}
	}
	
	private MainClick mMainClcik = new MainClick();
	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			Utilis.runVibrate(ManageAccount.this);
			int id = v.getId();
			switch (id) {
				case R.id.btn_new:
				{
					showNewDialog(null, false);
					break;
				}
				case R.id.btn_exit:
				{
					finish();
					break;
				}
			}
		}
	}
	
	private void showSortDialog(final int id, int sort){
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		final View root = this.getLayoutInflater().inflate(R.layout.dlg_edit_sort, null);
		EditText edit = (EditText)root.findViewById(R.id.edit_text); 
		edit.setText("" + sort);
		dialog.setTitle("Input");
		dialog.setView(root);
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// update 到資料庫
				int number = Utilis.toInt(((EditText)root.findViewById(R.id.edit_text)).getText().toString());
				SQLiteDatabase db = Utilis.getDB(ManageAccount.this);
				try{
					ContentValues value = new ContentValues();
					value.put("accsort", number);
						int success = db.update(com.cwbuyer.lib.TbName.ACCOUNT, value,
								"_id=?", new String[]{"" + id});
						if(success > 0){
							Toast.makeText(ManageAccount.this, "修改資料成功", Toast.LENGTH_SHORT).show();
							getAccountData();
						}else{
							Toast.makeText(ManageAccount.this, "修改資料失敗", Toast.LENGTH_SHORT).show();
						}
				}catch(Exception e){
					e.printStackTrace();
				}
				if(db != null){
					db.close();
				}
			}
		});
		dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		dialog.show();
	}
	
	private String[] mTypes = new String[]{"現金","現金(日幣、人民幣、港幣..)","信用卡","金融卡","儲值卡"};
	private void showNewDialog(final AccountData data, final boolean bEdit){
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		final View root = this.getLayoutInflater().inflate(R.layout.dlg_account, null);
//		final TextView print = (TextView)root.findViewById(R.id.text_print);
		Spinner spinner =  (Spinner)root.findViewById(R.id.spinner_pic);
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mTypes);
		adapter.setDropDownViewResource(R.layout.sst_simple_dropdown_item);
		spinner.setAdapter(adapter);
		
		if(data != null){
			((EditText)root.findViewById(R.id.edit_text)).setText(data.strText);
			((EditText)root.findViewById(R.id.edit_note)).setText(data.strNote);
			((EditText)root.findViewById(R.id.edit_rate)).setText(data.strRate);
			spinner.setSelection((data.nPic - 1));
		}
		
		dialog.setTitle("新增帳戶");
		dialog.setView(root);
		dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	        	  // 存取資料
	        	  String text = ((EditText)root.findViewById(R.id.edit_text)).getText().toString();
	        	  String rate = ((EditText)root.findViewById(R.id.edit_rate)).getText().toString();
	        	  String note = ((EditText)root.findViewById(R.id.edit_note)).getText().toString();
	        	  int nPic = ((Spinner)root.findViewById(R.id.spinner_pic)).getSelectedItemPosition() + 1;
	        	  if(text != null && text.length() > 0){
	        		  AccountData newData = new AccountData();
	        		  newData.strText = text;
	        		  newData.strNote = note;
	        		  newData.strRate = rate;
	        		  newData.nPic = nPic;
	        		  if(bEdit == true){
	        			  newData.nID = data.nID;
	        			  newData.nInit = data.nInit;
	        			  newData.nMoney = data.nMoney;
	        			  newData.nSort = data.nSort;
	        		  }
	        		  insertAccount(newData, bEdit);
	        	  }else{
	        		  Toast.makeText(ManageAccount.this, "帳戶名稱不能為空!", Toast.LENGTH_SHORT).show();
	        	  }
	          }
		});
		dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	          public void onClick(DialogInterface dialog, int which) {
	          }
			});
		dialog.show();
	}
}
