package com.yuji.ec;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.yuji.ec.common.CommonUtil;
import com.yuji.ec.utility.BaseActivity;
import com.yuji.ec.utility.EvernoteUtil;
import com.yuji.ec.utility.PasswordUtil;

public class UserPasswordActivity extends BaseActivity {
	private EditText userEditText = null;
	private EditText passwordEditText = null;
	private Button okButton = null;
	private Button cancelButton = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_password);
		
		userEditText = (EditText) this.findViewById(R.id.userUserEditText);
		passwordEditText = (EditText) this.findViewById(R.id.userPasswordEditText);
		okButton = (Button) this.findViewById(R.id.userOkButton);
		cancelButton = (Button) this.findViewById(R.id.userCancelButton);
		
		okButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				okButtonOnClick();
			}});
		userEditText.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable s) {
				setStatus();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				
			}});
		passwordEditText.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable s) {
				setStatus();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				
			}});
		cancelButton.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				cancelButtonOnClick();
			}});
		
		String username = PasswordUtil.getUsername(this);
		String password = PasswordUtil.getPassword(this);

		userEditText.setText(username);
		passwordEditText.setText(password);
		
		setStatus();
	}
	
	private void okButtonOnClick(){
		String username = userEditText.getText().toString();
		String password = passwordEditText.getText().toString();
		PasswordUtil.setUserAndPassword(this, username, password);
		
		EvernoteUtil util = EvernoteUtil.getInstance();
		util.setConfig(username, password);
		
		finish();
	}

	private void cancelButtonOnClick(){
		finish();		
	}
	
	private void setStatus(){
		String username = userEditText.getText().toString();
		String password = passwordEditText.getText().toString();

		boolean enabled = !CommonUtil.isNull(username) && !CommonUtil.isNull(password);
		okButton.setEnabled(enabled);
	}
}
