package jp.co.corecorp.s3pdf;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

///// pane02
/*
*  "card":{
*  	"P2":{
*  		"R":[
*  			{"item":"P001", "date":"2012/09/30","n1":0,"n3":12, "cat":0, "onece":0 },
*  		]
*  	}
*  }
*/

public class CardPane02 extends CardPane {
	private static final int MAXDATACOUNT = 3;
	ListAdapter	listAdapter = null;
	PaneRec[] paneRecs;

	class PaneRec {
		public String	item;
		public Date		date;
		public int[]	num;
		public int		cat;
		public int		onece;
		public PaneRec() {
			item 	= null;
			date	= null;
			num		= new int[4];
			for( int i = 0; i < 4; i++ ) {
				num[i] = -1;
			}
			cat		= 0;
			onece	= 0;
		}
	}
	
	@Override
	void loadPaneData(JSONObject paneData) {
		if( paneData != null ) {
			try {
				DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				JSONArray rec = paneData.getJSONArray("R");
				int len = rec.length();
				int i;
				for( i = 0; i < MAXDATACOUNT && i < len; i++ ) {
					JSONObject item = rec.getJSONObject(i);
					if( item.has("item") )
						paneRecs[i].item	= item.getString("item");
					else
						paneRecs[i].item	= null;
					if( item.has("date") )
						paneRecs[i].date	= df.parse(item.getString("date"));
					else
						paneRecs[i].date	= null;
					for( int n = 0; n < 4; n++ ) {
						String key = String.format("n%d", n);
						if( item.has(key) )
							paneRecs[i].num[n] = item.getInt(key);
						else
							paneRecs[i].num[n] = -1;
					}
					if( item.has("cat"))
						paneRecs[i].cat		= item.getInt("cat");
					else
						paneRecs[i].cat		= 0;
					if( item.has("onece") )
						paneRecs[i].onece	= item.getInt("onece");
					else
						paneRecs[i].onece	= 0;
				}
				for( ; i < MAXDATACOUNT ; i++ ) {
					paneRecs[i].item	= null;
					paneRecs[i].date	= null;
					for( int n = 0; n < 4; n++ ) {
						paneRecs[i].num[0] = -1;
					}
					paneRecs[i].cat		= 0;
					paneRecs[i].onece	= 0;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	JSONObject savePaneData() {
		boolean[] needSaveRec = new boolean[MAXDATACOUNT];
		boolean needSave = false;
		for( int i = 0; i < MAXDATACOUNT && !needSave; i++ ) {
			needSaveRec[i] = false;
			if( paneRecs[i].item != null ) {
				needSaveRec[i] = true;
				needSave = true;
			}
			if( paneRecs[i].date != null ) {
				needSaveRec[i] = true;
				needSave = true;
			}
			for( int n = 0; n < 4; n++ ) {
				if( paneRecs[i].num[n] != -1 ) {
					needSaveRec[i] = true;
					needSave = true;
					break;
				}
			}
			if( paneRecs[i].cat != 0 ) {
				needSaveRec[i] = true;
				needSave = true;
			}
			if( paneRecs[i].onece != 0 ) {
				needSaveRec[i] = true;
				needSave = true;
			}
		}

		if( !needSave )
			return null;

		JSONObject paneData = null;
		try {
			paneData = new JSONObject();
			JSONArray rec = new JSONArray();
			DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
			for( int i = 0; i < MAXDATACOUNT; i++ ) {
				if( needSaveRec[i] ) {
					JSONObject item = new JSONObject();
					if( paneRecs[i].item != null )
						item.put("item", paneRecs[i].item);
					if( paneRecs[i].date != null )
						item.put("date", df.format(paneRecs[i].date));
					for( int n = 0; n < 4; n++ ) {
						String key = String.format("n%d", n);
						if( paneRecs[i].num[n] != -1 )
							item.put(key, paneRecs[i].num[n]);
					}
					if( paneRecs[i].cat != 0 )
						item.put("cat", paneRecs[i].cat);
					if( paneRecs[i].onece != 0 )
						item.put("onece", paneRecs[i].onece);
					rec.put(item);
				}
			}
			paneData.put("R", rec);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
		return paneData;
	}

	private class ListAdapter extends BaseAdapter {
		protected LayoutInflater inflater;
		private SharePDF cdata;
		ListAdapter() {
			super();
			this.cdata		= CardPane02.this.cdata;
			this.inflater	=
				(LayoutInflater)cdata.getSystemService(CardActivity.LAYOUT_INFLATER_SERVICE);  
		}
		public long getItemId(int position) {
			return position;
		}
		public int getCount() {
			if( resource == null ) {
				return 0;
			}
			return MAXDATACOUNT;
		}

		public Object getItem(int position) {
			Object r = null;
			if( 0 <= position && position < MAXDATACOUNT ) {
				r = paneRecs[position];
			}
			return r;
		}

		public View getView(int position, View view, ViewGroup parent) {
			if( view == null ) {
				view = inflater.inflate(R.layout.card_pane02_row, null);  
			}
			if( 0 <= position && position < MAXDATACOUNT ) {
				DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				ImageView v_item = (ImageView)view.findViewById(R.id.pane02r_item);
				TextView v_name = (TextView)view.findViewById(R.id.pane02r_name);
				Button v_date = (Button)view.findViewById(R.id.pane02r_date);
				Button v_num1 = (Button)view.findViewById(R.id.pane02r_num1);
				Button v_num2 = (Button)view.findViewById(R.id.pane02r_num2);
				Button v_num3 = (Button)view.findViewById(R.id.pane02r_num3);
				Button v_num4 = (Button)view.findViewById(R.id.pane02r_num4);
				Button v_cat = (Button)view.findViewById(R.id.pane02r_catalog);
				Button v_onece = (Button)view.findViewById(R.id.pane02r_onece);
				boolean bcheck=false;
				if( v_item == null ) bcheck = true;
				if( v_name == null ) bcheck = true;
				if( v_date == null ) bcheck = true;
				if( v_num1 == null ) bcheck = true;
				if( v_num2 == null ) bcheck = true;
				if( v_num3 == null ) bcheck = true;
				if( v_num4 == null ) bcheck = true;
				if( v_cat == null ) bcheck = true;
				if( v_onece == null ) bcheck = true;
				if( bcheck ) {
					bcheck=false;
				}
				Bitmap itemBmp = null; 
				if( paneRecs[position].item != null ) {
					S3Resource ir = service.findResource(paneRecs[position].item);
					if( ir != null ) {
						try {
							v_name.setText(ir.getTitle());
							String imgFile = ir.getDemoFilePath();
							itemBmp = BitmapFactory.decodeFile(imgFile.toString());
						}
						catch(S3Exception e) {
							v_name.setText("");
						}
					} else {
						v_name.setText("");
					}
					if( paneRecs[position].date != null ) {
						v_date.setText(df.format(paneRecs[position].date));
					} else {
						v_date.setText("");
					}
					if( paneRecs[position].num[0] >= 0 ) {
						v_num1.setText(String.format("%d", paneRecs[position].num[0]));
					} else {
						v_num1.setText("");
					}
					if( paneRecs[position].num[1] >= 0 ) {
						v_num2.setText(String.format("%d", paneRecs[position].num[1]));
					} else {
						v_num2.setText("");
					}
					if( paneRecs[position].num[2] >= 0 ) {
						v_num3.setText(String.format("%d", paneRecs[position].num[2]));
					} else {
						v_num3.setText("");
					}
					if( paneRecs[position].num[3] >= 0 ) {
						v_num4.setText(String.format("%d", paneRecs[position].num[3]));
					} else {
						v_num4.setText("");
					}
					if( paneRecs[position].cat == 1 ) {
						v_cat.setText("要");
					} else if( paneRecs[position].cat == 2 ) {
						v_cat.setText("不要");
					} else {
						v_cat.setText("");
					}
					if( paneRecs[position].onece == 1 ) {
						v_onece.setText("要");
					} else if( paneRecs[position].onece == 2 ) {
						v_onece.setText("不要");
					} else {
						v_onece.setText("");
					}
				} else {
					v_name.setText("");
					v_date.setText("");
					v_num1.setText("");
					v_num2.setText("");
					v_num3.setText("");
					v_num4.setText("");
					v_cat.setText("");
					v_onece.setText("");
				}
				/*
				if( position == 0 ) {
					v_item.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.pal01_00, 0, 0);
				}
				*/
				if( itemBmp != null) {
					v_item.setImageBitmap(itemBmp);
				} else {
					v_item.setBackgroundResource(R.color.grid_cell);
				}
				view.setId(position);
				v_item.setOnClickListener(onItemClick);
				v_date.setOnClickListener(onDateClick);
				v_date.setOnLongClickListener(onDateLongClick);
				v_num1.setOnClickListener(onNumClick);
				v_num2.setOnClickListener(onNumClick);
				v_num3.setOnClickListener(onNumClick);
				v_num4.setOnClickListener(onNumClick);
				v_cat.setOnClickListener(onCatClick);
				v_onece.setOnClickListener(onOneceClick);
				return view;
			}
			return null;
		}
	}

	public CardPane02(CardActivity v, SharePDF cdata, S3Application service,
			S3Resource resource) {
		super(v, cdata, service, resource);
		listAdapter = new ListAdapter();
		paneRecs = new PaneRec[MAXDATACOUNT];
		for( int i = 0; i < MAXDATACOUNT; i++) 
			paneRecs[i] = new PaneRec();
	}

	@Override
	void onSelectItem(Object item) {
		String id = ((S3Resource)item).getResourceName();
		int pos = activity.isSelecterVisible();
		if( pos < 0 || MAXDATACOUNT <= pos ) return;
		paneRecs[pos].item = id;
		listAdapter.notifyDataSetChanged();
	}
	
	private RelativeLayout getRowView(View c) {
		while( c != null && !(c instanceof RelativeLayout) ) {
			ViewParent vp = c.getParent();
			c = (View)vp;
		}
		return (RelativeLayout)c;
	}
	
 	private View.OnClickListener onItemClick = new View.OnClickListener() {
		public void onClick(View v) {
			RelativeLayout rv = getRowView(v);
			if( rv == null ) return;
			int pos = rv.getId();
			if( pos < 0 || MAXDATACOUNT <= pos ) return;
			if( activity.isSelecterVisible() == pos) {
				activity.hideSelecter(false);
			} else {
				float tx = v.getLeft() + v.getWidth() * 0.6f;
				float ty = v.getTop() + v.getHeight()/2 + rv.getTop();
				activity.showSelecter(pos, tx, ty, "palette");
			}
		}
	};

	@Override
	void onSelectDate(Date dv, int pos) {
		if( pos < 0 || MAXDATACOUNT <= pos ) return;
		paneRecs[pos].date = dv;
		listAdapter.notifyDataSetChanged();
	}
 	private View.OnClickListener onDateClick = new View.OnClickListener() {
		public void onClick(View v) {
			RelativeLayout rv = getRowView(v);
			if( rv == null ) return;
			int pos = rv.getId();
			if( pos < 0 || MAXDATACOUNT <= pos ) return;
			Date dv = paneRecs[pos].date;
			if( dv == null ) dv = new Date();
			activity.showDatePicker(v, pos, dv);
		}
	};
 	private View.OnClickListener onNumClick = new View.OnClickListener() {
		public void onClick(View v) {
			RelativeLayout rv = getRowView(v);
			if( rv == null ) return;
			int pos = rv.getId();
			if( pos < 0 || MAXDATACOUNT <= pos ) return;

			int col = 0;
			switch(v.getId()) {
			case R.id.pane02r_num1:	col	= 0;	break;
			case R.id.pane02r_num2:	col	= 1;	break;
			case R.id.pane02r_num3:	col	= 2;	break;
			case R.id.pane02r_num4:	col	= 3;	break;
			}
			if( col < 0 || 4 <= col ) return;
			
			/*
			NumberPicker edtInput = new NumberPicker(activity);
			edtInput.setMaxValue(10);
			edtInput.setMinValue(0);
			new AlertDialog.Builder(activity)
			//.setIcon(R.drawable.icon)
			.setTitle("何を食べますか？")
			.setView(edtInput)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// OKボタンをクリックした時の処理 
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Cancel ボタンをクリックした時の処理
				}
			})
			.show();
			*/
			if( paneRecs[pos].num[col] < 5 ) {
				if( paneRecs[pos].num[col] < 0 )
					paneRecs[pos].num[col] = 1;
				else
					paneRecs[pos].num[col]++;
			} else {
				paneRecs[pos].num[col] = -1;
			}
			listAdapter.notifyDataSetChanged();
		}
	};
	
	private View.OnLongClickListener onDateLongClick = new View.OnLongClickListener() {
		public boolean onLongClick(View v) {
			RelativeLayout rv = getRowView(v);
			if( rv == null ) return true;
			int pos = rv.getId();
			if( pos < 0 || MAXDATACOUNT <= pos ) return true;

			if( paneRecs[pos].date != null ) {
				paneRecs[pos].date = null;
				listAdapter.notifyDataSetChanged();
			}
			return true;
		}
	};
	
	
 	private View.OnClickListener onCatClick = new View.OnClickListener() {
		public void onClick(View v) {
			RelativeLayout rv = getRowView(v);
			if( rv == null ) return;
			int pos = rv.getId();
			if( pos < 0 || MAXDATACOUNT <= pos ) return;
			if( paneRecs[pos].cat < 2 ) {
				paneRecs[pos].cat++;
			} else {
				paneRecs[pos].cat = 0;
			}
			listAdapter.notifyDataSetChanged();
		}
	}; 
	private View.OnClickListener onOneceClick = new View.OnClickListener() {
		public void onClick(View v) {
			RelativeLayout rv = getRowView(v);
			int pos = rv.getId();
			if( pos < 0 || MAXDATACOUNT <= pos ) return;
			if( paneRecs[pos].onece < 2 ) {
				paneRecs[pos].onece++;
			} else {
				paneRecs[pos].onece = 0;
			}
			listAdapter.notifyDataSetChanged();
		}
	};	
	@Override
	void initPane() {
		ListView v = (ListView)activity.findViewById(R.id.card02list);
		v.setAdapter(listAdapter);
	}

	@Override
	void startPane() {
	}

	@Override
	void endPane() {
	}

	@Override
	void showPane() {
		View v = activity.findViewById(R.id.card02pane);
		v.setVisibility(View.VISIBLE);
	}

	@Override
	void hidePane() {
		View v = activity.findViewById(R.id.card02pane);
		v.setVisibility(View.GONE);
	}
}
