
package com.kii.api_demos;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.kii.api_demos.object_storage.NotesList;
import com.kii.api_demos.user_management.SignUpActivity;
import com.kii.cloud.storage.Kii;
import com.kii.cloud.storage.KiiUser;

public class HomeActivity extends FragmentActivity implements OnClickListener {
    static {
        Kii.initialize(Constants.KII_APP_ID, Constants.KII_APP_KEY, Constants.KII_SITE);
    }

    EditText usernameEdit, passwordEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        usernameEdit = (EditText) findViewById(R.id.username);
        passwordEdit = (EditText) findViewById(R.id.password);
        findViewById(R.id.login).setOnClickListener(this);
        findViewById(R.id.register).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                new LoginTask().execute();
                break;
            case R.id.register:
                startActivity(new Intent(HomeActivity.this, SignUpActivity.class));
                break;
        }
    }

    class LoginTask extends AsyncTask<Void, Void, Void> {
        ProgressDialogFragment dialog = null;
        boolean succ = false;

        @Override
        protected Void doInBackground(Void... params) {
            KiiUser mUser = null;
            try {
                mUser = KiiUser.logIn(usernameEdit.getText().toString(), passwordEdit
                        .getText()
                        .toString());
                if (mUser != null) {
                    mUser.refresh();
                    succ = true;
                }
            } catch (Exception e) {
                succ = false;
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = ProgressDialogFragment.newInstance(getString(R.string.in_progressing));
            dialog.show(getSupportFragmentManager(), "dialog");
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (succ) {
                startActivity(new Intent(HomeActivity.this, NotesList.class));
            } else {
                Toast.makeText(HomeActivity.this, R.string.login_failed,
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

}
