package jp.co.corecorp.s3pdf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

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

import android.net.Uri;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class CardActivity extends Activity {
	private static final int REQUEST_GALLERY = 0;
	private SharePDF	 cdata	= null;
	private int viewMode = CardPane.PANE01;
	private boolean updateCard = false;
	private boolean saveCard = false;
	private String resourceName;
	private JSONObject cardData;
	private int selecterVisible = -1;
	private boolean imageVisible = false;
	private CardPane[] panes = new CardPane[5];
	private ItemAdapter itemAdapter = null;
	private ImageAdapter imageAdapter = null;
	
	protected class ItemAdapter extends ResourceAdapter {
		public ItemAdapter(SharePDF cdata, String tag) {
			super(cdata, tag);
		}
		public View getView(int position, View view, ViewGroup parent) {
			if( view == null ) {
				view = inflater.inflate(R.layout.item_selecter_row, null);  
			}
			S3Resource rsc = (S3Resource)getItem(position);
			String imgFile;
			try {
				imgFile = rsc.getDemoFilePath();
			} catch (S3Exception e) {
				return null;
			}
			
			ImageView iv;
			TextView tv;
			iv = (ImageView)view.findViewById(R.id.item_image);
			S3Context con = cdata.getS3Con();
			Context ctx = con.getContext();
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgFile.toString(), opt);
			
			final float density = ctx.getResources().getDisplayMetrics().density;  
			int imgSize = (int)(256 * density + 0.5f);
			int scaleW = opt.outWidth / imgSize + 1;
			int scaleH = opt.outHeight / imgSize + 1;
			int scale;
			if( scaleW > scaleH )
				scale = scaleW;
			else
				scale = scaleW;
			opt.inSampleSize = scale;
			opt.inJustDecodeBounds = false;
			Bitmap bmp = BitmapFactory.decodeFile(imgFile.toString(), opt);
			iv.setImageBitmap(bmp);

			tv = (TextView)view.findViewById(R.id.item_name);
			tv.setText(rsc.getTitle());
			tv = (TextView)view.findViewById(R.id.item_desc);
			tv.setText(rsc.getDescription());
			view.setId(position);
			return view;
		}
	}
	
	protected class ImageAdapter extends GadgetAdapter {
		public ImageAdapter(SharePDF cdata, String tag) {
			super(cdata, tag);
		}
		public View getView(int position, View view, ViewGroup parent) {
			if( view == null ) {
				view = inflater.inflate(R.layout.gadgetlist_row, null);  
			}
			String imgTag = (String)getItem(position);
			if( imgTag == null ) return null;
			File imgFile;
			try {
				imgFile = rsc.findStreamGadetFile(imgTag);
			} catch (S3Exception e) {
				return null;
			} catch (S3TypeException e) {
				return null;
			}
			
			S3Context con = cdata.getS3Con();
			Context ctx = con.getContext();
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgFile.toString(), opt);
			
			final float density = ctx.getResources().getDisplayMetrics().density;  
			int imgSize = (int)(350 * density + 0.5f);
			int scaleW = opt.outWidth / imgSize + 1;
			int scaleH = opt.outHeight / imgSize + 1;
			int scale;
			if( scaleW > scaleH )
				scale = scaleW;
			else
				scale = scaleW;
			opt.inSampleSize = scale;
			opt.inJustDecodeBounds = false;
			Bitmap bmp = BitmapFactory.decodeFile(imgFile.toString(), opt);
			
			ImageView iv = (ImageView)view.findViewById(R.id.gadget_img);
			iv.setImageBitmap(bmp);
			
			String modText = "";
			S3Gadget g = rsc.findGadget(imgTag);
			if( g != null ) {
				Date modiTime = g.getLastModifyTime();
				if( modiTime != null ) {
					DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
					modText = df.format(modiTime);
				}
			}
			TextView tv = (TextView)view.findViewById(R.id.gadget_text);
			tv.setText(modText);
			
			return view;
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cdata = (SharePDF)getApplication();
        if( cdata == null ) {
        	finish();
        	return;
        }
        
    	S3Resource rsc = null;
		Intent intent = getIntent();
		if (Intent.ACTION_VIEW.equals(intent.getAction())) {
			Bundle pm = intent.getExtras();
			String rsn = pm.getString("ResourceName");
			if( rsn != null ) {
				resourceName = rsn;
				rsc = getResource();
			}
			switch(pm.getInt("view_mode", 0)) {
			case 0:	viewMode = CardPane.PANE01;	break;
			case 1:	viewMode = CardPane.PANE02;	break;
			case 2:	viewMode = CardPane.PANE03;	break;
			case 3:	viewMode = CardPane.PANE04;	break;
			case 4:	viewMode = CardPane.PANE05;	break;
			}
		}
		if( rsc == null ) {
			finish();
			return;
		}
		
		S3Application svc = getService();
        panes[0] = new CardPane01(this, cdata, svc, rsc);
        panes[1] = new CardPane02(this, cdata, svc, rsc);
        panes[2] = new CardPane03(this, cdata, svc, rsc);
        panes[3] = new CardPane04(this, cdata, svc, rsc);
        panes[4] = new CardPane05(this, cdata, svc, rsc);
        
        setContentView(R.layout.activity_card);
    	Button selector;
    	selector = (Button)findViewById(R.id.card01sel);
    	selector.setOnClickListener(onPaneSelect);
    	selector = (Button)findViewById(R.id.card02sel);
    	selector.setOnClickListener(onPaneSelect);
    	selector = (Button)findViewById(R.id.card03sel);
    	selector.setOnClickListener(onPaneSelect);
    	selector = (Button)findViewById(R.id.card04sel);
    	selector.setOnClickListener(onPaneSelect);
    	selector = (Button)findViewById(R.id.card05sel);
    	selector.setOnClickListener(onPaneSelect);
    	
		ListView lvSel = (ListView)findViewById(R.id.item_selecter_list);
		lvSel.setOnItemClickListener(onItemClick);
	    
		ListView lvImg = (ListView)findViewById(R.id.imageList);
	    lvImg.setOnItemLongClickListener(onItemLongClick);
	    
		View vThumb = findViewById(R.id.thumbIcon);
		vThumb.setOnClickListener(onThumbClick);
		
		cardData = null;
		try {
			cardData = rsc.findJSONGadget("card");
		} catch (S3TypeException e) {
		}
		loadPaneData(CardPane.PANEALL);
        setViewMode(viewMode);
		int i;
		for(i = 0; i < 5; i++) {
			if( panes[i] != null )
				panes[i].initPane();
		}
		hideSelecter(true);
		hideImageLists(true);
    }

	private View.OnClickListener onPaneSelect = new View.OnClickListener() {
    	public void onClick(View v) {
    		int id = v.getId();
    		switch(id) {
    		case R.id.card01sel:	setViewMode(CardPane.PANE01);	break;
    		case R.id.card02sel:	setViewMode(CardPane.PANE02);	break;
    		case R.id.card03sel:	setViewMode(CardPane.PANE03);	break;
    		case R.id.card04sel:	setViewMode(CardPane.PANE04);	break;
    		case R.id.card05sel:	setViewMode(CardPane.PANE05);	break;
    		}
    	}
   	};
   	
	S3Application getService() {
		S3ServiceManager sm = cdata.getS3Con().getServiceManager();
		return sm.findService(SharePDF.SharePdfService);
	}
	S3Resource getResource() {
		S3Application svc = getService();
		if( svc == null ) {
			return null;
		}
		return svc.findResource(resourceName);
	}
	public int isSelecterVisible() {
		return selecterVisible;
	}
	
    private OnItemClickListener onItemClick = new OnItemClickListener() {
        public void onItemClick(AdapterView<?>parent, View view, int position, long id) {
        	int vn = viewMode;
        	CardPane pn = panes[vn];
        	if( pn  != null ) {
        		pn.onSelectItem(itemAdapter.getItem(position));
        	}
		}
   	};
   	
	public void showSelecter(int r, float x, float y, String tag) {
		if( itemAdapter == null || !itemAdapter.tag.equals(tag) ) {
			itemAdapter = new ItemAdapter(cdata, tag);
			ListView lv = (ListView)findViewById(R.id.item_selecter_list);
			lv.setAdapter(itemAdapter);
		}
		View a = findViewById(R.id.arrowIcon);
		View v = findViewById(R.id.floatSelecterView);
		a.setY(y);
		if( selecterVisible == -1 ) {
			class An implements Animation.AnimationListener {
				View v;
				int pos;
				public An(View v, int pos) {
					this.v = v;
					this.pos = pos;
				}
				public void onAnimationStart(Animation animation) { }
				public void onAnimationRepeat(Animation animation) {}
				public void onAnimationEnd(Animation animation) {
					v.setX(pos);
					v.setAnimation(null);
				}
			};
			Animation anim = new TranslateAnimation(v.getX(), x, 0, 0);
			anim.setDuration(200);
			anim.setAnimationListener(new An(v,(int)x));
			v.startAnimation(anim);
		} else {
			v.setX(x);
		}
		selecterVisible = r;
	}
	public void hideSelecter(boolean quick) {
		DisplayMetrics metrics = new DisplayMetrics();  
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		View v = findViewById(R.id.floatSelecterView);
		if( quick ) {
			v.setX(metrics.widthPixels);
			v.setAnimation(null);
		} else {
			class An implements Animation.AnimationListener {
				View v;
				int pos;
				public An(View v, int pos) {
					this.v = v;
					this.pos = pos;
				}
				public void onAnimationStart(Animation animation) { }
				public void onAnimationRepeat(Animation animation) {}
				public void onAnimationEnd(Animation animation) {
					v.setX(pos);
					v.setAnimation(null);
				}
			};
			Animation anim = new TranslateAnimation(v.getX(), metrics.widthPixels, 0, 0);
			anim.setDuration(200);
			anim.setAnimationListener(new An(v,metrics.widthPixels));
			v.startAnimation(anim);
		}
		selecterVisible = -1;
	}
	
    private View.OnClickListener onThumbClick = new View.OnClickListener() {
    	public void onClick(View v) {
    		if( imageVisible )
    			CardActivity.this.hideImageLists(false);
    		else
    			CardActivity.this.showImageLists(false);
    	}
   	};
	
	void showImageLists(boolean quick) {
		ListView lv = (ListView)findViewById(R.id.imageList);
		if( imageAdapter == null ) {
			imageAdapter = new ImageAdapter(cdata, SharePDF.RESOURCE_IMAGE_ATTACHTAG);
			imageAdapter.setResource(getResource());
			lv.setAdapter(imageAdapter);
		}
		ViewGroup v = (ViewGroup)findViewById(R.id.floatImageView);
		int w = lv.getWidth();
		if( !imageVisible && !quick ) {
			class An implements Animation.AnimationListener {
				View fv;
				View lv;
				public An(View fv, View lv) {
					this.fv = fv;
					this.lv = lv;
				}
				public void onAnimationStart(Animation animation) {
					lv.setVisibility(View.VISIBLE);
				}
				public void onAnimationRepeat(Animation animation) {}
				public void onAnimationEnd(Animation animation) {
					fv.setAnimation(null);
				}
			};
			Animation anim = new TranslateAnimation(-w, 0, 0, 0);
			anim.setDuration(200);
			anim.setAnimationListener(new An(v, lv));
			v.startAnimation(anim);
		} else {
			lv.setVisibility(View.VISIBLE);
		}
		((ImageView)findViewById(R.id.thumbIcon)).setImageResource(R.drawable.ic_arrow_close);
		imageVisible = true;
	}
	
	void hideImageLists(boolean quick) {
		View v = findViewById(R.id.floatImageView);
		View lv = findViewById(R.id.imageList);
		int w = lv.getWidth();
		if( !quick ) {
			class An implements Animation.AnimationListener {
				View fv;
				View lv;
				public An(View fv, View lv) {
					this.fv = fv;
					this.lv = lv;
				}
				public void onAnimationStart(Animation animation) {}
				public void onAnimationRepeat(Animation animation) {}
				public void onAnimationEnd(Animation animation) {
					lv.setVisibility(View.GONE);
					fv.setAnimation(null);
				}
			};
			Animation anim = new TranslateAnimation(0, -w, 0, 0);
			anim.setDuration(200);
			anim.setAnimationListener(new An(v,lv));
			v.startAnimation(anim);
		} else {
			lv.setVisibility(View.GONE);
			v.setAnimation(null);
		}
		((ImageView)findViewById(R.id.thumbIcon)).setImageResource(R.drawable.ic_arrow_open);
		imageVisible = false;
	}

    private DatePickerDialog.OnDateSetListener onDateSelect = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        	int vn = viewMode;
        	CardPane pn = panes[vn];
        	if( pn  != null ) {
        		Date d = new Date();
        		d.setYear(year-1900);
        		d.setMonth(monthOfYear);
        		d.setDate(dayOfMonth);
        		pn.onSelectDate(d, datePickerPos);
        	}
		}
   	};
	
	int datePickerPos;
	void showDatePicker(View v, int pos, Date base) {
		datePickerPos = pos;
        final Calendar calendar = Calendar.getInstance();
        final int year = base.getYear()+1900;
        final int month = base.getMonth();
        final int day = base.getDate();
	    final DatePickerDialog datePickerDialog = new DatePickerDialog(
	            this,
	            onDateSelect,
	            year, month, day);
	        datePickerDialog.show();
	}
	
	JSONObject getPaneData(JSONObject cd, int pane) {
		JSONObject paneData = null;
		if( cd != null ) {
			String key = String.format("P%d", pane+1);
			try {
				paneData = cd.getJSONObject(key);
			} catch (JSONException e) {
			}
		}
		return paneData;
	}
	
	void loadPaneData(int pane) {
		int i;
		for( i = 0; i < 5; i++ ) {
			if( pane == CardPane.PANEALL || pane == i ) {
				JSONObject pd = getPaneData(cardData, i);
				if( panes[i] != null ) 
					panes[i].loadPaneData(pd);
			}
		}
	}
	void savePaneData(int pane) throws S3Exception, S3TypeException {
		int i;
		int paneDatas = 0;
		for( i = 0; i < 5; i++ ) {
			String key = String.format("P%d", i+1);
			if( pane == CardPane.PANEALL || pane == i ) {
				JSONObject pd = null;
				if( panes[i] != null ) 
					pd = panes[i].savePaneData();
				if( cardData != null )
					cardData.remove(key);
				if( pd != null ) {
					try {
						if( cardData == null )
							cardData = new JSONObject();
						cardData.put(key, pd);
					} catch (JSONException e) {
					}
				}
			}
			if( cardData != null &&	cardData.has(key) ) {
				paneDatas++;
			}
		}
		S3Resource rsc = getResource();
		if( paneDatas > 0 ) {
			rsc.setGadget("card", cardData);
			if( cardData != null && cardData.has("P1") )
				rsc.setTag("P1");
			else
				rsc.removeTag("P1");
			if( cardData != null && cardData.has("P2") )
				rsc.setTag("P2");
			else
				rsc.removeTag("P2");
			if( cardData != null && cardData.has("P3") )
				rsc.setTag("P3");
			else
				rsc.removeTag("P3");
			if( cardData != null && cardData.has("P4") )
				rsc.setTag("P4");
			else
				rsc.removeTag("P4");
			if( cardData != null && cardData.has("P5") )
				rsc.setTag("P5");
			else
				rsc.removeTag("P5");
		} else {
			rsc.removeGadget("card");
			rsc.removeTag("P1");
			rsc.removeTag("P2");
			rsc.removeTag("P3");
			rsc.removeTag("P4");
			rsc.removeTag("P5");
		}
		rsc.saveGadget();
	}
	
	void removePaneData(int pane) throws S3Exception, S3TypeException {
		if( cardData != null ) {
			int i;
			for( i = 0; i < 5; i++ ) {
				String key = String.format("P%d", i+1);
				if( pane == CardPane.PANEALL || pane == i ) {
					if( cardData.has("key"))
						cardData.remove(key);
				}
			}
		}
		S3Resource rsc = getResource();
		rsc.removeGadget("card");
		rsc.removeTag("P1");
		rsc.removeTag("P2");
		rsc.removeTag("P3");
		rsc.removeTag("P4");
		rsc.removeTag("P5");
		rsc.saveGadget();
	}
	
    void setViewMode(int mode) {
    	hideSelecter(true);
    	Button[] selector = new Button[5];
    	selector[0] = (Button)findViewById(R.id.card01sel);
    	selector[1] = (Button)findViewById(R.id.card02sel);
    	selector[2] = (Button)findViewById(R.id.card03sel);
    	selector[3] = (Button)findViewById(R.id.card04sel);
    	selector[4] = (Button)findViewById(R.id.card05sel);
    	int i;
    	for( i = 0; i < 5; i++ ) {
    		if( i == mode ) {
    			selector[i].setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.bf_select_on);
    			if( panes[i] != null ) panes[i].showPane();
    		} else {
    			selector[i].setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, R.drawable.bf_select_off);
    			if( panes[i] != null ) panes[i].hidePane();
    		}
    	}
    	viewMode = mode;
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if( requestCode == REQUEST_GALLERY && resultCode == RESULT_OK ) {
			Uri uri = data.getData();
			InputStream in = null;
			try {
				in = getContentResolver().openInputStream(uri);
			} catch (FileNotFoundException e1) {
				return;
			}
			S3Resource resource = getResource();
			String imgTag = resource.createUniqueId();
			try {
				resource.setGadget(imgTag, in);
				resource.setGadgetTag(imgTag, SharePDF.RESOURCE_IMAGE_ATTACHTAG);
				resource.setTag(SharePDF.RESOURCE_IMAGE_ATTACHTAG);
			} catch (S3Exception e1) {
				return;
			} catch (S3TypeException e) {
				e.printStackTrace();
				return;
			}
			if( !imageVisible ) {
				showImageLists(false);
			}
			imageAdapter.notifyDataSetChanged();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}  
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_card, menu);
        return true;
    }
    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if( item.getItemId() == android.R.id.home) {
			finish();
            return true;
		}
		if( item.getItemId() == R.id.menu_photo_add ) {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intent, REQUEST_GALLERY);		
            return true;
		}
		if( item.getItemId() == R.id.menu_card_ok ) {
			S3Resource rsc = getResource();
			try {
				savePaneData(CardPane.PANEALL);
				rsc.setTag("card_ent");
				finish();
				return true;
			} catch (S3Exception e) {
				e.printStackTrace();
			} catch (S3TypeException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
		}
		if( item.getItemId() == R.id.menu_card_del ) {
			S3Resource rsc = getResource();
			try {
				removePaneData(CardPane.PANEALL);
				rsc.removeTag("card_ent");
				finish();
				return true;
			} catch (S3Exception e) {
				e.printStackTrace();
			} catch (S3TypeException e) {
				e.printStackTrace();
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private OnItemLongClickListener onItemLongClick = new OnItemLongClickListener() {
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			String imgTag = (String)imageAdapter.getItem(position);
			try {
				S3Resource rsc = getResource();
				rsc.removeGadget(imgTag);
				rsc.removeTag(SharePDF.RESOURCE_IMAGE_ATTACHTAG);
			} catch (S3Exception e) {
			} catch (S3TypeException e) {
			}
			imageAdapter.notifyDataSetChanged();
			return true;
		}
	};
    
	@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("view_mode", viewMode);
        /*
        EditText editText = (EditText) findViewById(ID_EDIT);
        Editable value = editText.getText();
        outState.putString(KEY_EDIT, value.toString());
        */
    }
	
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        viewMode = savedInstanceState.getInt("view_mode", CardPane.PANE01);
        /*
        // Bundleに保存した値を取得する
        String value = savedInstanceState.getString(KEY_EDIT);
 
        // EditTextに値を設定する
        EditText editText = (EditText) findViewById(ID_EDIT);
        editText.setText(value);
        */
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    }
    
    @Override
    public void onStart() {
		super.onStart();
		ActionBar actionBar = this.getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
   		//cdata.getS3Con().setSyncHandler(onSyncHandler);
    }
    
	@Override
	protected void onPause() {
		super.onPause();
   		//cdata.getS3Con().setSyncHandler(null);
	}
}
