package jp.co.corecorp.s3pdf;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import jp.co.corecorp.s3pdf.CardActivity.ItemAdapter;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
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.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class MainActivity extends Activity {
	private SharePDF	 cdata	= null;
    private ProgressDialog dialog = null;
	private ListAdapter cardAdapter = null;
	private PaletteAdapter paletteAdapter = null;
	private int nRegisterCB = 0;
	private static final int VIEWMODE_LOGIN = 0;
	private static final int VIEWMODE_REGUSER = 1;
	private static final int VIEWMODE_MAIN = 2;
	private int viewMode = VIEWMODE_LOGIN;
    private boolean paletteVisible = false;
    
	protected class PaletteAdapter extends ResourceAdapter {
		public PaletteAdapter(SharePDF cdata) {
			super(cdata, "palette");
		}
		public View getView(int position, View view, ViewGroup parent) {
			S3Resource rsc = (S3Resource)getItem(position);
			if( rsc == null ) return null;
			if( view == null ) {
				view = inflater.inflate(R.layout.item_selecter_row, null);  
			}
			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;
		}
	}
	
	private class ListAdapter extends ResourceAdapter {
		public ListAdapter(SharePDF cdata) {
			super(cdata, SharePDF.SharePdfContentTag);
		}

		public View getView(int position, View view, ViewGroup parent) {
			S3Resource rsc = (S3Resource)getItem(position);
			if( rsc == null ) return null;
			if( view == null ) {
				view = inflater.inflate(R.layout.cardlist_row, null);  
			}
			TextView tvTitle = (TextView)view.findViewById(R.id.docTitle);
			tvTitle.setText(rsc.getTitle());
			TextView tvDesc = (TextView)view.findViewById(R.id.docDesc);
			tvDesc.setText(rsc.getDescription());
			TextView tvSyncTime = (TextView)view.findViewById(R.id.syncDate);
			Date d = rsc.getLastSyncTime();
			DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			tvSyncTime.setText(df.format(d));
			ImageView ic;
			ic = (ImageView)view.findViewById(R.id.docIcon);
			if( rsc.hasTag("star") ) {
				ic.setImageResource(R.drawable.ic_star_blue);
			} else {
				ic.setImageResource(R.drawable.ic_star_dgray);
			}
			ic.setOnClickListener(onStarItemClick);

			ic = (ImageView)view.findViewById(R.id.statusIcon1);
			if( rsc.hasTag(SharePDF.RESOURCE_IMAGE_ATTACHTAG) ) {
				ic.setImageResource(R.drawable.ic_photo);
			} else {
				ic.setImageResource(R.drawable.ic_photo_gray);
			}
			ic.setOnClickListener(onCardIconClick);
			
			ic = (ImageView)view.findViewById(R.id.statusIcon2);
			if( rsc.hasTag("P1") ) {
				ic.setImageResource(R.drawable.ic_card_pause);
			} else {
				ic.setImageResource(R.drawable.ic_card_pause_g);
			}
			ic.setOnClickListener(onCardIconClick);

			ic = (ImageView)view.findViewById(R.id.statusIcon3);
			if( rsc.hasTag("P2") || rsc.hasTag("P3") ) {
				ic.setImageResource(R.drawable.ic_card_change);
			} else {
				ic.setImageResource(R.drawable.ic_card_change_g);
			}
			ic.setOnClickListener(onCardIconClick);
			
			ic = (ImageView)view.findViewById(R.id.statusIcon4);
			if( rsc.hasTag("P4") ) {
				ic.setImageResource(R.drawable.ic_card_mes);
			} else {
				ic.setImageResource(R.drawable.ic_card_mes_g);
			}
			ic.setOnClickListener(onCardIconClick);

			ic = (ImageView)view.findViewById(R.id.statusIcon5);
			if( rsc.hasTag("P5") ) {
				ic.setImageResource(R.drawable.ic_card_secede);
			} else {
				ic.setImageResource(R.drawable.ic_card_secede_g);
			}
			ic.setOnClickListener(onCardIconClick);
			
			view.setId(position);
			return view;
		}
	}
	   
    private S3ConnectHandler onConnectHandler = new S3ConnectHandler() {
    	@Override
		public void onError(S3Context con, String msg) {
    		Log.d("Main.onConnectHandler.onError", msg);
    		if( dialog != null ) {
    			dialog.dismiss();
    			dialog = null;
    		}
			Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
			return;
		}
    	@Override
		public void onConnect(S3Context con) {
    		String m = String.format("connect ok and mode=%d", viewMode);
    		Log.d("Main.onConnectHandler.onConnect", m);
    		EditText user = (EditText)findViewById(R.id.editUserId);
    		EditText pass = (EditText)findViewById(R.id.editPasswd);
    		if( viewMode == VIEWMODE_LOGIN ) {
        		if( dialog != null ) {
        			dialog.setMessage("ログイン中です");
        		}
	    		con.login(user.getText().toString(), pass.getText().toString(), onLoginHandler);
    		} else {
        		if( dialog != null ) {
        			dialog.setMessage("アカウント登録中です");
        		}
        		EditText name1 = (EditText)findViewById(R.id.editUserName1);
        		EditText name2 = (EditText)findViewById(R.id.editUserName2);
	    		con.registerAccount(user.getText().toString(), pass.getText().toString(), name1.getText().toString(), name2.getText().toString(), onLoginHandler);
    		}
		}
	};
    private S3LoginHandler onLoginHandler = new S3LoginHandler() {
    	@Override
		public void onError(S3Context con, String msg) {
    		Log.d("Main.onLoginHandler.onError", msg);
    		if( dialog != null ) {
    			dialog.dismiss();
    			dialog = null;
    		}
			Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
			return;
		}
    	@Override
		public void onLogin(S3Context con) {
    		String m = String.format("ok and mode=%d", viewMode);
    		Log.d("Main.onLoginHandler.onLogin", m);
    		cdata.setS3Con(con);
    		if( viewMode == VIEWMODE_LOGIN ) {
        		if( dialog != null ) {
        			dialog.setMessage("SharPDFサービスに接続中です");
        		}
        		nRegisterCB = 0;
    			con.registerService(SharePDF.SharePdfService, onRegisterServiceHandler);
    			con.registerService("UserSpace", onRegisterServiceHandler);
    		}
		}
	};
	private S3RegisterHandler onRegisterServiceHandler = new S3RegisterHandler() {
    	@Override
		public void onError(S3Context con, String msg) {
    		Log.d("Main.onRegisterServiceHandler.onError", msg);
    		nRegisterCB++;
    		if( dialog != null ) {
    			dialog.dismiss();
    			dialog = null;
    		}
			Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
			return;
		}
    	@Override
		public void onRegisterComplete(S3Context con, String svc) {
    		Log.d("Main.onRegisterServiceHandler.onRegisterComplete", "ok");
    		nRegisterCB++;
    		if( nRegisterCB == 2 ) {
    			S3Application svcPdf = con.getServiceManager().findService(SharePDF.SharePdfService); 
    			S3Application svcUsr = con.getServiceManager().findService("UserSpace");
    			if( svcPdf != null &&
    				svcUsr != null ) {
    				con.sync(svcPdf);
    				con.sync(svcUsr);
    				toMainMode();
    			}
	    		if( dialog != null ) {
	    			dialog.dismiss();
	    			dialog = null;
	    		}
    		}
		}
	};
	
	private S3SyncHandler onSyncHandler = new S3SyncHandler() {
		@Override
		public void onSyncProgress(S3Context ctx, String svn, String rsn) {
		}
		@Override
		public void onSyncComplete(S3Context ctx, String svn) {
		}
	};

	private void doLogin() {
		Log.d("Main.doLogin", "begin");
		dialog  = new ProgressDialog(MainActivity.this);
		dialog.setCancelable(false);
//		dialog.setTitle("S3 SharePDF");
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setMessage("接続中です");
		dialog.show();
		cdata.getS3Con().connect("192.168.0.10", 1119, onConnectHandler);
		Log.d("Main.doLogin", "end");
	}
	private View.OnClickListener onLogin = new View.OnClickListener() {
    	public void onClick(View v) {
    		doLogin();
    	}
   	};
    private View.OnClickListener onSwitchMode = new View.OnClickListener() {
    	public void onClick(View v) {
    		if( viewMode == VIEWMODE_REGUSER )
    			toRegisterMode();
    		else
    			toLoginMode();
    	}
   	};
   	
   	private void toLoginMode() {
        findViewById(R.id.textUserName1).setVisibility(View.GONE);
        findViewById(R.id.editUserName1).setVisibility(View.GONE);
        findViewById(R.id.textUserName2).setVisibility(View.GONE);
        findViewById(R.id.editUserName2).setVisibility(View.GONE);
        ((Button)findViewById(R.id.btnLogin)).setText(getString(R.string.login_sub));
        ((TextView)findViewById(R.id.textLoginOrRegister)).setText(getString(R.string.registerLink));
        if( viewMode != VIEWMODE_LOGIN ) {
        	findViewById(R.id.editUserId).requestFocus();
        }
        viewMode = VIEWMODE_LOGIN;
   	}
   	private void toRegisterMode() {
        findViewById(R.id.textUserName1).setVisibility(View.VISIBLE);
        findViewById(R.id.editUserName1).setVisibility(View.VISIBLE);
        findViewById(R.id.textUserName2).setVisibility(View.VISIBLE);
        findViewById(R.id.editUserName2).setVisibility(View.VISIBLE);
        ((Button)findViewById(R.id.btnLogin)).setText(getString(R.string.register_sub));
        ((TextView)findViewById(R.id.textLoginOrRegister)).setText(getString(R.string.loginLink));
        if( viewMode != VIEWMODE_REGUSER ) {
        	findViewById(R.id.editUserName1).requestFocus();
        }
        viewMode = VIEWMODE_REGUSER;
   	}
   	
    private OnItemClickListener onItemClick = new OnItemClickListener() {
        public void onItemClick(AdapterView<?>parent, View view, int position, long id) {
    		Intent intent = new Intent(MainActivity.this.cdata,PdfActivity.class);
    		intent.setAction(Intent.ACTION_VIEW);
    		S3Context con = cdata.getS3Con();
    		S3ServiceManager sm = con.getServiceManager();
			S3Application svc = sm.findService(SharePDF.SharePdfService);
			if( svc != null ) {
				S3Resource rsc = svc.getResource(position);
				if( rsc != null ) {
		    		intent.putExtra("ResourceName", rsc.getResourceName());
		    		startActivity(intent);
				}
			}
		}
   	};
   	
    private View.OnClickListener onStarItemClick = new View.OnClickListener() {
		public void onClick(View v) {
			ViewParent pv = v.getParent();	// ImageView -> RelativeLayout
			pv = pv.getParent();			// RelativeLayout -> LinearLayout
			LinearLayout rv = (LinearLayout)pv;
			int pos = rv.getId();
			S3Resource rsc = (S3Resource)cardAdapter.getItem(pos);
			if( rsc == null ) return;
			try {
				if( rsc.hasTag("star") )
					rsc.removeTag("star");
				else
					rsc.setTag("star");
				
			} catch (S3Exception e) {
				return;
			}
			cardAdapter.notifyDataSetChanged();
		}
	};
    private View.OnClickListener onCardIconClick = new View.OnClickListener() {
		public void onClick(View v) {
			ViewParent pv = v.getParent();	// ImageView -> LinearLayout
			pv = pv.getParent();			// LinearLayout -> RelativeLayout
			pv = pv.getParent();			// RelativeLayout -> LinearLayout
			LinearLayout rv = (LinearLayout)pv;
			int pos = rv.getId();
			S3Resource rsc = (S3Resource)cardAdapter.getItem(pos);
			if( rsc == null ) return;
			
			if( v.getId() == R.id.statusIcon1 ) {
				// image icon
				return;
			}
			
			int mode = 0;
			switch(v.getId()) {
			case R.id.statusIcon2:	mode = 0;	break;
			case R.id.statusIcon3:
				mode = 1;
				if( rsc.hasTag("P3")) mode = 2;
				if( rsc.hasTag("P2")) mode = 1;
				break;
			case R.id.statusIcon4:	mode = 3;	break;
			case R.id.statusIcon5:	mode = 4;	break;
			}
    		Intent intent = new Intent(MainActivity.this.cdata,CardActivity.class);
    		intent.setAction(Intent.ACTION_VIEW);
    		S3Context con = cdata.getS3Con();
    		S3ServiceManager sm = con.getServiceManager();
			S3Application svc = sm.findService(SharePDF.SharePdfService);
			if( svc != null ) {
				if( rsc != null ) {
		    		intent.putExtra("ResourceName", rsc.getResourceName());
		    		intent.putExtra("view_mode", mode);
		    		startActivity(intent);
				}
			}
		}
	};
   	
   	private void toMainMode() {
		ListView listView = (ListView)findViewById(R.id.cardlist);
		if( listView == null ) {
	        setContentView(R.layout.activity_main);
			listView = (ListView)findViewById(R.id.cardlist);
		    cardAdapter = new ListAdapter(cdata);
		    listView.setAdapter(cardAdapter);
		    listView.setOnItemClickListener(onItemClick);
		    paletteAdapter = null;
		}
        viewMode = VIEWMODE_MAIN;
        hidePalette(true);
   	}
   	
	public void showPalette(boolean quick) {
		if( paletteAdapter == null ) {
			paletteAdapter = new PaletteAdapter(cdata);
			ListView lv = (ListView)findViewById(R.id.paletteItemList);
			lv.setAdapter(paletteAdapter);
		}
		View v = findViewById(R.id.floatPalleteView);
		
		int x = v.getLeft();
		int w = v.getWidth();
		if( !paletteVisible && !quick ) {
			class An implements Animation.AnimationListener {
				View v;
				public An(View v) {
					this.v = v;
				}
				public void onAnimationStart(Animation animation) {
					v.setVisibility(View.VISIBLE);
				}
				public void onAnimationRepeat(Animation animation) {}
				public void onAnimationEnd(Animation animation) {
					v.setAnimation(null);
				}
			};
			Animation anim = new TranslateAnimation(-w, 0, 0, 0);
			anim.setDuration(200);
			anim.setAnimationListener(new An(v));
			v.startAnimation(anim);
		} else {
			v.setVisibility(View.VISIBLE);
		}
		paletteVisible = true;
	}
	
	public void hidePalette(boolean quick) {
		View v = findViewById(R.id.floatPalleteView);
		int x = v.getLeft();
		int w = v.getWidth();
		if( !quick ) {
			class An implements Animation.AnimationListener {
				View v;
				public An(View v) {
					this.v = v;
				}
				public void onAnimationStart(Animation animation) {}
				public void onAnimationRepeat(Animation animation) {}
				public void onAnimationEnd(Animation animation) {
					v.setVisibility(View.INVISIBLE);
					v.setAnimation(null);
				}
			};
			Animation anim = new TranslateAnimation(0, -w, 0, 0);
			anim.setDuration(200);
			anim.setAnimationListener(new An(v));
			v.startAnimation(anim);
		} else {
			v.setVisibility(View.INVISIBLE);
			v.setAnimation(null);
		}
		paletteVisible = false;
	}    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cdata = (SharePDF)getApplication();
        S3Context con = cdata.getS3Con();
        if( con == null ) {
    		Log.d("Main.onCreate", "create S3Context");
    		S3ContextBuilder conBuilder = new S3ContextBuilder(cdata);
    		try {
    			con = conBuilder.createContext("0.1");
    		}
    		catch(S3Exception e) {
    			return;
    		}
    		cdata.setS3Con(con);
        }
    }
	
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if( item.getItemId() == R.id.menu_show_palette ) {
			if( viewMode == VIEWMODE_MAIN ) {
				if( paletteVisible ) {
					hidePalette(false);
				} else {
					showPalette(false);
				}
			}
		}
		return super.onOptionsItemSelected(item);
	}
    
	@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("view_mode", viewMode);
    	Log.d("Main.onSaveInstanceState", String.format("viewMode=%d", viewMode));
    }
	
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        viewMode = savedInstanceState.getInt("view_mode", VIEWMODE_LOGIN);
    	Log.d("Main.onRestoreInstanceState", String.format("viewMode=%d", viewMode));
    }
    
    @Override
    public void onStart() {
		super.onStart();
    }
    
	@Override
	protected void onResume() {
   		if( cardAdapter != null )
   			cardAdapter.notifyDataSetChanged();
   		cdata.getS3Con().setSyncHandler(onSyncHandler);
		S3Context con = cdata.getS3Con();
        if( con.isLoggedin() ) {
        	viewMode = VIEWMODE_MAIN;
        } else if( viewMode != VIEWMODE_LOGIN && viewMode != VIEWMODE_REGUSER ) {
        	viewMode = VIEWMODE_LOGIN;
        }
        
        if( viewMode == VIEWMODE_LOGIN || viewMode == VIEWMODE_REGUSER ) { 
	        //StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
	        setContentView(R.layout.activity_login);
	        findViewById(R.id.textLoginOrRegister).setOnClickListener(onSwitchMode);
	        findViewById(R.id.btnLogin).setOnClickListener(onLogin);
	        if( viewMode == VIEWMODE_LOGIN ) {
	        	toLoginMode();
	        } else {
	        	toRegisterMode();
	        }
	    	EditText ep = (EditText)findViewById(R.id.editPasswd);
	    	ep.setOnEditorActionListener(new OnEditorActionListener() {  
	    	    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
	    	        if (actionId == EditorInfo.IME_ACTION_GO) {
	    	            doLogin();
	    	        }  
	    	        return true;  
	    	    }
	    	});
        } else if( viewMode == VIEWMODE_MAIN ) {
        	toMainMode();
        }
		super.onResume();
	}
	@Override
	protected void onPause() {
		super.onPause();
   		cdata.getS3Con().setSyncHandler(null);
	}
}
