package tw.darkk6.xposed.motweaker;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener, OnCheckedChangeListener {

	private CheckBox chText,chSign;
	private EditText txtSign;
	private Button btnOK,btnExit;
	private SharedPreferences prefs;
	
	@SuppressLint({ "WorldReadableFiles"})
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		prefs=getSharedPreferences("prefs", Context.MODE_WORLD_READABLE);
		checkAndWriteDefaultPrefs();
		
		initViews();
	}

	@Override
	public void onClick(View v) {
		if(v==btnOK){
			saveSetting();
			Toast.makeText(this, "設定已儲存", Toast.LENGTH_SHORT).show();
			this.finish();
		}else{
			Toast.makeText(this, "變更已取消", Toast.LENGTH_SHORT).show();
			this.finish();
		}
	}
	@Override
	public void onCheckedChanged(CompoundButton view, boolean isChecked) {
		txtSign.setEnabled(isChecked);
	}
	
	private void saveSetting(){
		SharedPreferences.Editor edit=prefs.edit();
		edit.putBoolean("stopTextFilter", chText.isChecked());
		edit.putBoolean("customSign", chSign.isChecked());
		edit.putString("signature", txtSign.getText().toString());
		edit.commit();
	}
	
	private void initViews(){
		chText=(CheckBox)findViewById(R.id.checkBox1);
		chSign=(CheckBox)findViewById(R.id.checkBox2);
		txtSign=(EditText)findViewById(R.id.editText1);
		btnOK=(Button)findViewById(R.id.button1);
		btnExit=(Button)findViewById(R.id.button2);
		
		btnOK.setOnClickListener(this);
		btnExit.setOnClickListener(this);
		chSign.setOnCheckedChangeListener(this);
		
		chText.setChecked(prefs.getBoolean("stopTextFilter", true));
		chSign.setChecked(prefs.getBoolean("customSign", true));
		txtSign.setText(prefs.getString("signature","Sent from my Android"));
		txtSign.setEnabled(chSign.isChecked());
		
	}
	
	private void checkAndWriteDefaultPrefs(){
		//建立預設的 preference 設定檔
		SharedPreferences.Editor edit=prefs.edit();
		if(!prefs.contains("stopTextFilter")){
			edit.putBoolean("stopTextFilter", true);
		}
		if(!prefs.contains("customSign")){
			edit.putBoolean("customSign", true);
		}
		if(!prefs.contains("signature")){
			edit.putString("signature", "Sent from my Android");
		}
		
		edit.commit();
	}
}
