package com.longdong.studio.section1_calculator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
 
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.longdong.studio.section1_calculator.R;

public class UnitConvActivity extends  Activity {
	
	
	static String [] areaUnits={"mm^2","cm^2","m^2","km^2","hectare(s)","acre(s)"},
			lengthUnits={"mm","cm","m","km","in","ft","yd","mi"},
			volumeUnits={"ml","l","fl oz","pt","qt","gal"},
			weightUnits={"g","kg","t","oz","lb"},
			tempUnits={"°C","°F"};
	
	static double [] areaRatios={0.0001,0.01,1,1000000,10000,4046.8564224},
			lengthRatios={0.001,0.01,1,1000,0.0254,0.3048,0.9144,1609.344},
			volumeRatios={1,1000,28.4130625,568.26125,1136.5225,4546.09},
			weightRatios={1,1000,1000000,28.349523125,453.59237};
	
	static String [][] units={lengthUnits,areaUnits,volumeUnits,weightUnits,tempUnits};
	static double [][] ratios={lengthRatios,areaRatios,volumeRatios,weightRatios};
	
	int nowType=0,nowFrom=0,nowTo=0;	// 当前类型、源单位、目的单位
	double nowNum,nowAns;				// 当前输入、当前输出

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_unit_conv);
		
	    /* 将计算器界面显示的数值拷贝到换算器界面： */
	    Intent intent = getIntent();
	    double value = intent.getDoubleExtra("calcValue",0);
	    Toast toast=Toast.makeText(this, "The number has been copied here.", Toast.LENGTH_SHORT);
	    toast.show();
	    
	    /* 输入框数值发生变化时动态更新换算结果： */
	    EditText et1=(EditText) findViewById(R.id.editText1);
	    et1.setText(Double.toString(value));
	    et1.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				conv();
			}
	    	
	    });
	    
	    /* 切换类型时动态更新换算结果： */
	    RadioGroup rg1=(RadioGroup) findViewById(R.id.radioGroup1);
	    rg1.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO Auto-generated method stub
				switch (arg1){
				case R.id.radio0:
					nowType=0; break;
				case R.id.radio1:
					nowType=1; break;
				case R.id.radio2:
					nowType=2; break;
				case R.id.radioButton1:
					nowType=3; break;
				case R.id.radioButton2:
					nowType=4; break;
				}
				refreshSpinners();
				SharedPreferences sp=getSharedPreferences("unit_conv",Context.MODE_PRIVATE);
				Editor ed=sp.edit();
				ed.putInt("type", nowType);
				ed.commit();
			}
	    	
	    });
	    /* 两个Spinner切换选择项时动态更新换算结果： */
	    Spinner sp1=(Spinner) findViewById(R.id.spinner1);
	    sp1.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				nowFrom=arg2;
				conv();
				SharedPreferences sp=getSharedPreferences("unit_conv",Context.MODE_PRIVATE);
				Editor ed=sp.edit();
				ed.putInt("from", nowFrom);
				ed.commit();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				nowFrom=0;
			}
	    	
	    });
		Spinner sp2=(Spinner) findViewById(R.id.Spinner01);
		sp2.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				nowTo=arg2;
				conv();
				SharedPreferences sp=getSharedPreferences("unit_conv",Context.MODE_PRIVATE);
				Editor ed=sp.edit();
				ed.putInt("to", nowTo);
				ed.commit();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				nowTo=0;
			}
	    	
	    });
		
		/* 读取上一次的换算单位状态 */
		SharedPreferences sp=getSharedPreferences("unit_conv",Context.MODE_PRIVATE);
		switch(sp.getInt("type",units.length-1)){
		case 0: rg1.check(R.id.radio0); break;
		case 1: rg1.check(R.id.radio1); break;
		case 2: rg1.check(R.id.radio2); break;
		case 3: rg1.check(R.id.radioButton1); break;
		case 4: rg1.check(R.id.radioButton2); break;
		}
		//refreshSpinners();
		
		sp1.setSelection(sp.getInt("from", 1));
		sp2.setSelection(sp.getInt("to", 0));
		// conv();
	}

	void refreshSpinners() {
		/* 切换单位类别(NowType)后，更新Spinner的列表 */
		ArrayAdapter<String> aa=new ArrayAdapter<String> (this,android.R.layout.simple_spinner_dropdown_item,units[nowType]);
		Spinner sp1=(Spinner) findViewById(R.id.spinner1);
		Spinner sp2=(Spinner) findViewById(R.id.Spinner01);
		sp1.setAdapter(aa);
		sp2.setAdapter(aa);
		conv();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.unit_conv, menu);
		return true;
	}

    @SuppressWarnings("deprecation")
	@Override
	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_copy: // 复制
            	cm.setText(Double.toString(nowAns));
                return true;
            case R.id.action_paste: // 粘贴
            	try {
            		((EditText) findViewById(R.id.editText1)).setText(cm.getText());
            		conv();
            	} catch(Exception e){
            		// Nothing
            	}
            	return true;
            case R.id.action_copy_back:
            	this.setResult(RESULT_OK,this.getIntent().putExtra("result", nowAns));
            	this.finish();
            	return true;
            default:
                return super.onOptionsItemSelected(item);
        }
	}
	
	void conv(){
		try {
			nowNum=Double.parseDouble(
					((EditText) findViewById(R.id.editText1)).getText().toString()
					);
			if (nowType!=units.length-1){	// 温度换算特殊处理
				nowAns=nowNum*ratios[nowType][nowFrom]/ratios[nowType][nowTo];
			} else {						// 其他单位的换算（通用）
				if (nowFrom==0 && nowTo==1) nowAns=nowNum/5*9+32;
				else if (nowFrom==1 && nowTo==0) nowAns=(nowNum-32)/9*5;
				else nowAns=nowNum;
			}
			/* 显示换算结果： */
			TextView tv1=(TextView) findViewById(R.id.textView1);
			tv1.setText("="+Double.toString(nowAns)+" "+units[nowType][nowTo]);
			TextView tv2=(TextView) findViewById(R.id.textView2);
			tv2.setText(units[nowType][nowFrom]);
		} catch(Exception e){
			//Toast toast=Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT);
		    //toast.show();
		}
	}
}
