package com.longdong.studio.section1_calculator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.text.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import com.longdong.studio.section1_calculator.R;


public class MainActivity extends  Activity {

	double nowNumber,prevNumber;	// 褰撳墠鏄剧ず鏁板?硷紙double鏍煎紡锛夈?佷笂涓?涓搷浣滄暟
	String nowString;				// 褰撳墠鏄剧ず鏁板?硷紙String鏍煎紡锛?
	char savedOp;					// 淇濆瓨鐨勮繍绠楃
	boolean isUserInput,isDotInputed,hasPrevNumber;	// 褰撳墠鏁板瓧鏄敤鎴疯緭鍏ョ殑銆佸綋鍓嶅凡杈撳叆灏忔暟鐐广?佹湁涓婁竴涓搷浣滄暟
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        allClear(null);
        ((Button) findViewById(R.id.ButtonDel)).setOnLongClickListener(
        		new View.OnLongClickListener() {
					
					@Override
					public boolean onLongClick(View v) {
						allClear(null);
				        return true;
					}
				}
        );
    }

    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        // 鍙充笂瑙掑姛鑳借彍鍗曟樉绀烘寜閽搷搴斿嚱鏁?
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    /*
    void changeDisplay(){
    	TextView disp=(TextView) findViewById(R.id.textViewDisplayArea);
    	if (isUserInput)
    		disp.setText((CharSequence) nowString);
    	else 
        	disp.setText((CharSequence) Double.toString(nowNumber));
    }
    */
    
    void refreshAndSync(){	// 鍒锋柊鏄剧ず骞跺悓姝tring鏍煎紡鍜宒ouble鏍煎紡鐨勫綋鍓嶆暟鍊?
    	TextView disp=(TextView) findViewById(R.id.textViewDisplayArea);
    	if (isUserInput)
    		nowNumber=Double.parseDouble(nowString);
    	else
    		nowString=Double.toString(nowNumber);
    	disp.setText(nowString);
    }
    
	public void addNumber(View view) {
		Button button = (Button) view;
		char newChar = ((String) button.getText()).charAt(0);
		if (!isUserInput){	// 濡傛灉鏄繍绠楃粨鏋滃垯鍏堟竻闄ゆ墍鏈夋暟鎹?
			boolean hasPrev=hasPrevNumber;	// 浣嗗鏋滃彧鏄腑闂寸粨鏋滐紝瑕佷繚鐣欎腑闂寸姸鎬?
			allClear(null);
			hasPrevNumber=hasPrev;
		}
		if (isDotInputed) {	// 鏈?澶氶檺鍒跺埌12浣嶏紙涓嶅惈灏忔暟鐐癸級
			if (nowString.length() >= 13)
				return;
		} else {
			if (nowString.length() >= 12)
				return;
		}
		switch (newChar) {
		case '0':					// 閬垮厤鍑虹幇杈撳叆浜嗗涓?"0"鐨勬儏鍐?
			if (nowString == "0")   // 姣斿"000000"
				return;
			break;
		case '.':
			if (isDotInputed)		// 濡傛灉宸茬粡杈撳叆浜嗗皬鏁扮偣灏变笉鑳藉啀杈撳叆
				return;
			else
				isDotInputed = true;
			break;
		default:
			if (nowString == "0")	// 閬垮厤鍓嶅0
				nowString = "";
		}
		nowString += newChar;
		refreshAndSync();
	}

	public void doCalc(View view) {
		isUserInput = false;
		if (hasPrevNumber) {
			calc();
			refreshAndSync();
		}
		hasPrevNumber = true;
		prevNumber = nowNumber;
		switch (view.getId()) {
		case R.id.ButtonPlus:
			savedOp = '+';
			break;
		case R.id.ButtonMinus:
			savedOp = '-';
			break;
		case R.id.ButtonMultiply:
			savedOp = '*';
			break;
		case R.id.ButtonDivide:
			savedOp = '/';
			break;
		case R.id.ButtonCalc:
		default:
			savedOp = '=';
			hasPrevNumber = false;
			break;
		}
		// ((TextView)
		// findViewById(R.id.textViewCalcHistory)).setText(""+savedOp);
	}
	
	void calc(){
		double result=0;
		switch (savedOp){
		case '+':
			result=prevNumber+nowNumber;
			break;
		case '-':
			result=prevNumber-nowNumber;
			break;
		case '*':
			result=prevNumber*nowNumber;
			break;
		case '/':
			result=prevNumber/nowNumber;
			break;
		}
		TextView history=((TextView) findViewById(R.id.textViewCalcHistory));
		history.setText(
				history.getText()+"\n"+
				Double.toString(prevNumber)+savedOp+Double.toString(nowNumber)+
				"="+Double.toString(result)
		);
		final ScrollView sv1 = (ScrollView) findViewById(R.id.scrollView1);
        sv1.post(new Runnable() {  
                public void run() {  
                	sv1.fullScroll(ScrollView.FOCUS_DOWN);  
                }  
        });  
		nowNumber=result;
	}
	
    
    public void allClear(View view) {	// AC锛堝叏閮ㄦ竻闆讹級
    	nowString="0";
    	nowNumber=0;
    	// prevNumber=0;
        isDotInputed=false;
        isUserInput=true;
        hasPrevNumber=false;
    	refreshAndSync();
    }
    
    public void delNumber(View view) {
    	if (isUserInput){
	    	if (nowString.length()==0) return; // 閬垮厤瓒婄晫
	    	if (nowString.charAt(nowString.length()-1)=='.')
	    		isDotInputed=false;	// 濡傛灉鍒犻櫎浜嗗皬鏁扮偣锛屼慨鏀瑰搴旂殑鐘舵??
	    	nowString=nowString.substring(0,nowString.length()-1);
	    	if (nowString.length()==0) nowString="0";	// 閬垮厤绌轰覆
	    	refreshAndSync();
    	} else {	// 濡傛灉鏄繍绠楃粨鏋滃氨鍏ㄩ儴娓呴浂
    		allClear(null);
    	}
    }
    
    public void calcSqrt(View view) {
    	isUserInput=false;
    	nowNumber=Math.sqrt(nowNumber);
    	refreshAndSync();
    }
    
    public void toggleSign(View view) {
    	if (isUserInput){
    		if (nowNumber==0) return;	// 閬垮厤"-0"
    		if (nowString.charAt(0)=='-')
    			nowString=nowString.substring(1, nowString.length());
    		else
    			nowString='-'+nowString;
    	} else 
    		nowNumber*=-1;
    	refreshAndSync();
    }

    static final int CONVERTER_REQUEST=0;
    
    @SuppressWarnings("deprecation")
	public boolean onOptionsItemSelected(MenuItem item) {
    	ClipboardManager cm=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_about: // 鍏充簬
                
                return true;
            case R.id.action_copy: // 澶嶅埗
            	cm.setText(nowString);
            	// cm.setPrimaryClip(ClipData.newPlainText("number",nowString));
                return true;
            case R.id.action_paste: // 绮樿创
            	try {
            		double test=Double.parseDouble((String) cm.getText()); // 鍏堟祴璇曪紝濡傛灉鏃犳硶杞崲涓烘暟瀛楀氨涓嶈绮樿创
	            	/* 杩欓噷鐨勪唬鐮佸拰addNumber()涓?鑷? */
	            	if (!isUserInput){	// 濡傛灉鏄繍绠楃粨鏋滃垯鍏堟竻闄ゆ墍鏈夋暟鎹?
	        			boolean hasPrev=hasPrevNumber;	// 浣嗗鏋滃彧鏄腑闂寸粨鏋滐紝瑕佷繚鐣欎腑闂寸姸鎬?
	        			allClear(null);
	        			hasPrevNumber=hasPrev;
	        		}
	            	nowString=(String) cm.getText();
	            	refreshAndSync();
            	} catch(Exception e){
            		// Nothing
            	}
            	return true;
            case R.id.action_conv: // 鍒囨崲鍒拌浆鎹㈠櫒
                Intent intent = new Intent(this, UnitConvActivity.class);
                intent.putExtra("calcValue", nowNumber); // 鍙戦?佸綋鍓嶆暟鍊?
                startActivityForResult(intent,CONVERTER_REQUEST);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override  
    protected void onActivityResult(int requestCode,int resultCode,Intent data){  
          
        switch(requestCode){  
        case CONVERTER_REQUEST:
        	if (resultCode==RESULT_OK){
	            /*鍙栧緱鏉ヨ嚜B椤甸潰鐨勬暟鎹紝骞舵樉绀哄埌鐢婚潰*/
	            Bundle bundle = data.getExtras();  
	            
	            try {
	            	/*鑾峰彇Bundle涓殑鏁版嵁锛屾敞鎰忕被鍨嬪拰key*/  
	            	allClear(null);
	            	nowString=Double.toString(bundle.getDouble("result"));
	            	refreshAndSync();
	            } catch(Exception e){
	            	
	            }
        	}
        }  
    }  
}
