package jp.co.corecorp.s3pdf;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.view.KeyEvent;
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.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

///// pane03
/*
*  "card":{
*  	"P3":{
*  		"R":[
*  			{"item":"P001", "n1":0,"n3":12, "type":0, "begin":"10-2w","end":"10-3w", "other":0 },
*  		]
*  	}
*  }
*/

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

	class PaneRec {
		public String	item;
		public int[]	num;
		public int		type;
		public String	begin;
		public String	end;
		public int		other;
		public PaneRec() {
			item 	= null;
			num		= new int[4];
			for( int i = 0; i < 4; i++ ) {
				num[i] = -1;
			}
			type	= 0;
			begin	= null;
			end		= null;
			other	= 0;
		}
	}
	
	@Override
	void loadPaneData(JSONObject paneData) {
		if( paneData != null ) {
			try {
				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("type"))
						paneRecs[i].type	= item.getInt("type");
					else
						paneRecs[i].type	= 0;
					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("begin"))
						paneRecs[i].begin	= item.getString("begin");
					else
						paneRecs[i].begin	= null;
					if( item.has("end"))
						paneRecs[i].end		= item.getString("end");
					else
						paneRecs[i].end		= null;
					if( item.has("other"))
						paneRecs[i].other	= item.getInt("other");
					else
						paneRecs[i].other	= 0;
				}
				for( ; i < MAXDATACOUNT ; i++ ) {
					paneRecs[i].item = null;
					paneRecs[i].type	= 0;
					for( int n = 0; n < 4; n++ ) {
						paneRecs[i].num[n] = -1;
					}
					paneRecs[i].begin	= null;
					paneRecs[i].end		= null;
					paneRecs[i].other	= 0;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	JSONObject savePaneData() {
		boolean[] needSaveRec = new boolean[MAXDATACOUNT];
		boolean needSave = false;
		for( int i = 0; i < MAXDATACOUNT; i++ ) {
			needSaveRec[i] = false;
			if( paneRecs[i].item != 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].type != 0 ) {
				needSaveRec[i] = true;
				needSave = true;
			}
			if( paneRecs[i].begin != null ) {
				needSaveRec[i] = true;
				needSave = true;
			}
			if( paneRecs[i].end != null ) {
				needSaveRec[i] = true;
				needSave = true;
			}
			if( paneRecs[i].other != 0 ) {
				needSaveRec[i] = true;
				needSave = true;
			}
		}

		if( !needSave )
			return null;
		
		JSONObject paneData = null;
		try {
			paneData = new JSONObject();
			JSONArray rec = new JSONArray();
			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].type != 0 )
						item.put("type", paneRecs[i].type);
					for( int n = 0; n < 4; n++ ) {
						if( paneRecs[i].num[n] != -1 ) {
							String key = String.format("n%d", n);
							item.put(key, paneRecs[i].num[n]);
						}
					}
					if( paneRecs[i].begin != null && !paneRecs[i].begin.isEmpty() )
						item.put("begin", paneRecs[i].begin);
					if( paneRecs[i].end != null && !paneRecs[i].end.isEmpty() )
						item.put("end", paneRecs[i].end);
					if( paneRecs[i].other != 0)
						item.put("other", paneRecs[i].other);
					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		= CardPane03.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_pane03_row, null);  
			}
			if( 0 <= position && position < MAXDATACOUNT ) {
				ImageView v_item = (ImageView)view.findViewById(R.id.pane03r_item);
				TextView v_name = (TextView)view.findViewById(R.id.pane03r_name);
				Button v_type = (Button)view.findViewById(R.id.pane03r_type);
				TextView v_num1 = (TextView)view.findViewById(R.id.pane03r_num1);
				TextView v_num2 = (TextView)view.findViewById(R.id.pane03r_num2);
				TextView v_num3 = (TextView)view.findViewById(R.id.pane03r_num3);
				TextView v_num4 = (TextView)view.findViewById(R.id.pane03r_num4);
				Button v_w1 = (Button)view.findViewById(R.id.pane03r_w1);
				Button v_w2 = (Button)view.findViewById(R.id.pane03r_w2);
				Button v_other = (Button)view.findViewById(R.id.pane03r_other);
				boolean bcheck=false;
				if( v_item == null ) bcheck = true;
				if( v_name == null ) bcheck = true;
				if( v_type == 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_w1 == null ) bcheck = true;
				if( v_w2 == null ) bcheck = true;
				if( v_other == 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].type == 1 ) {
						v_type.setText("開始");
					} else if( paneRecs[position].type == 2 ) {
						v_type.setText("終了");
					} else if( paneRecs[position].type == 3 ) {
						v_type.setText("変更");
					} else {
						v_type.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].begin != null ) {
						v_w1.setText(paneRecs[position].begin);
					} else {
						v_w1.setText("");
					}
					if( paneRecs[position].end != null ) {
						v_w2.setText(paneRecs[position].end);
					} else {
						v_w2.setText("");
					}
					if( paneRecs[position].other == 1 ) {
						v_other.setText("休み");
					} else if( paneRecs[position].other == 2 ) {
						v_other.setText("要");
					} else if( paneRecs[position].other == 3 ) {
						v_other.setText("不要");
					} else {
						v_other.setText("");
					}
				} else {
					v_name.setText("");
					v_type.setText("");
					v_num1.setText("");
					v_num2.setText("");
					v_num3.setText("");
					v_num4.setText("");
					v_w1.setText("");
					v_w2.setText("");
					v_other.setText("");
				}
				if( itemBmp != null) {
					v_item.setImageBitmap(itemBmp);
				} else {
					v_item.setBackgroundResource(R.color.grid_cell);
				}
				view.setId(position);
				v_item.setOnClickListener(onItemClick);
				v_type.setOnClickListener(onTypeClick);
				v_num1.setOnFocusChangeListener(onNumFocusChange);
				v_num2.setOnFocusChangeListener(onNumFocusChange);
				v_num3.setOnFocusChangeListener(onNumFocusChange);
				v_num4.setOnFocusChangeListener(onNumFocusChange);
				/*
				v_num1.setOnClickListener(onNumClick);
				v_num2.setOnClickListener(onNumClick);
				v_num3.setOnClickListener(onNumClick);
				v_num4.setOnClickListener(onNumClick);
				*/
				v_w1.setOnClickListener(onWeekClick);
				v_w2.setOnClickListener(onWeekClick);
				v_other.setOnClickListener(onOtherClick);
				return view;
			}
			return null;
		}
	}	
	public CardPane03(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, "cat");
			}
		}
	};

 	private View.OnClickListener onTypeClick = 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;
			
			switch( paneRecs[pos].type ) {
			case 0:	paneRecs[pos].type = 1; break;
			case 1:	paneRecs[pos].type = 2; break;
			case 2:	paneRecs[pos].type = 3; break;
			default:paneRecs[pos].type = 0; break;
			}
			listAdapter.notifyDataSetChanged();
		}
	};
	
 	private View.OnFocusChangeListener onNumFocusChange = new View.OnFocusChangeListener() {
		public void onFocusChange(View v, boolean hasFocus) {
			if( !hasFocus ) {
				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.pane03r_num1: col = 0;	break;
				case R.id.pane03r_num2: col = 1;	break;
				case R.id.pane03r_num3: col = 2;	break;
				case R.id.pane03r_num4: col = 3;	break;
				}
				String text = ((EditText)v).getText().toString();
				int value = -1;
				if( !text.isEmpty() ) {
					try {
						value = Integer.parseInt(text);
					}
					catch(NumberFormatException e) {
						value = -1;
					}
				}
				paneRecs[pos].num[col] = value;
			}
		}
	};
	
	@Override
	void onSelectDate(Date dv, int pos) {
		int s = 0;
		if( pos >= MAXDATACOUNT )  {
			s = 1;
			pos -= MAXDATACOUNT;
		}
		if( pos < 0 || MAXDATACOUNT <= pos ) return;
		DateFormat df = new SimpleDateFormat("MM - W'w'");
		String v = df.format(dv);
		if( s == 0 )
			paneRecs[pos].begin = v;
		else
			paneRecs[pos].end = v;
		listAdapter.notifyDataSetChanged();
	}

 	private View.OnClickListener onWeekClick = 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.pane03r_w1:	col	= 0;	break;
			case R.id.pane03r_w2:	col	= 1;	break;
			}
			if( col == 1 )
				pos += MAXDATACOUNT;
			activity.showDatePicker(v, pos, new Date());
			/*
			if( paneRecs[pos].cat < 2 ) {
				paneRecs[pos].cat++;
			} else {
				paneRecs[pos].cat = 0;
			}
			listAdapter.notifyDataSetChanged();
			*/
		}
	}; 
	private View.OnClickListener onOtherClick = new View.OnClickListener() {
		public void onClick(View v) {
			RelativeLayout rv = getRowView(v);
			int pos = rv.getId();
			if( pos < 0 || MAXDATACOUNT <= pos ) return;
			switch( paneRecs[pos].other ) {
			case 0:	paneRecs[pos].other = 1; break;
			case 1:	paneRecs[pos].other = 2; break;
			case 2:	paneRecs[pos].other = 3; break;
			default:paneRecs[pos].other = 0; break;
			}
			listAdapter.notifyDataSetChanged();
		}
	};	
	@Override
	void initPane() {
		ListView v = (ListView)activity.findViewById(R.id.card03list);
		v.setAdapter(listAdapter);
	}

	@Override
	void startPane() {
	}

	@Override
	void endPane() {
	}

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

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