package com.usai.redant.raimage;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.usai.util.AES;
import com.usai.util.Crypto;
import com.usai.util.Network;
import com.usai.util.dbUtil;
import com.usai.util.dbgUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class FullScreenLoginActivity extends Activity {


    private UserLoginTask			mAuthTask	= null;
//    ArrayAdapter<String> adapter		= null;

    // Values for email and password at the time of the login attempt.
    private String					m_sName;
    private String					m_sPassword;

    // UI references.
    private EditText	m_etName;
    private EditText m_etPassword;
    private EditText	m_etServer;
//    private View					mLoginFormView;
    private View					mLoginStatusView;
    private TextView				mLoginStatusMessageView;
    private Switch m_swSave;
    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean>
    {
        // int err_code = ERR_CODE_NONE;
        JSONObject json	= null;

        // int netconnect;

        @Override
        protected Boolean doInBackground(Void... params)
        {

            json = Network.Login(m_sName, m_sPassword);
            try {
                if (json.getInt("result") == Network.RESULT_TRUE)
                    return true;
                else
                    return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(final Boolean success)
        {
            Log.i("onPostExecute", "entry");
            mAuthTask = null;
            showProgress(false);

            if (success)
            {
                String encryptUser = "";
                String encryptPass = "";
                try
                {
                    encryptUser = AES.encrypt("usai2010", m_sName);
                    encryptPass = AES.encrypt("usai2010", m_sPassword);
                }
                catch (Exception e1)
                {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                /*SQLiteDatabase db = dbUtil.OpenDB(LoginActivity.this, null,
                        true);
                Cursor cursor = db.query("users", new String[] { "_id" },
                        "name='" + encryptUser + "'", null, null, null, "_id",
                        null);
                if (cursor.moveToNext())
                {
                    int _id = cursor.getInt(0);
                    String sql = "update users set pass='" + encryptPass
                            + "' where _id=" + _id;
                    db.execSQL(sql);
                }
                else
                {
                    String sql = "insert into users(name,pass) values('"
                            + encryptUser + "','" + encryptPass + "')";
                    db.execSQL(sql);
                }
                dbUtil.CloseCursor(cursor);
                dbUtil.CloseDB(db);*/

                SharedPreferences pref = RedAntApplication.getInstance()
                        .getSharedPreferences("RA Image", 0);
                SharedPreferences.Editor editor = pref.edit();

                if (m_swSave.isChecked()&&!TextUtils.isEmpty(encryptPass)&&!TextUtils.isEmpty(encryptUser))
                {
                    editor.putString("user", encryptUser);
                    editor.putString("password", encryptPass);
                    editor.putBoolean("kepppass", true);
                }
                else
                {
                    editor.putString("user", null);
                    editor.putString("password", null);
                    editor.putBoolean("kepppass", false);
                }

                editor.commit();

                RedAntApplication.user = m_sName;
                RedAntApplication.password = m_sPassword;
                RedAntApplication.server_info = json;
                Intent intent = new Intent();
                intent.setClass(FullScreenLoginActivity.this, ModeActivity.class);

                dbgUtil.fileLog("user "+m_sName+" login @server "+RedAntApplication.active_address);
                startActivity(intent);
                finish();
            }
            else
            {
                int result = 0;
                try {
                    result = json.getInt("result");
                } catch (Exception e) {
                    e.printStackTrace();
                    result = Network.RESULT_NET_ERROR;

                }
                switch (result)
                {
                    case Network.RESULT_NET_ERROR:
                    case Network.RESULT_NET_NOTAVAILABLE:
                    {
                       /* SQLiteDatabase db = dbUtil.OpenDB(LoginActivity.this,
                                null, true);

                        String encryptUser = "";
                        try
                        {
                            encryptUser = Crypto.encrypt("apexu", m_sName);
                        }
                        catch (Exception e1)
                        {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        Cursor cursor = db.query("users", new String[] {
                                        "pass", "_id" }, "name= '" + encryptUser + "'",
                                null, null, null, "_id desc", null);
                        if (cursor.moveToNext())
                        {
                            String pass = "";
                            try
                            {
                                pass = Crypto.decrypt("apexp",
                                        cursor.getString(0));
                            }
                            catch (Exception e)
                            {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            if (pass.equals(m_sPassword))
                            {
                                dbUtil.CloseCursor(cursor);
                                dbUtil.CloseDB(db);
                                RedAntApplication.user = m_sName;
                                RedAntApplication.password = m_sPassword;
                                Intent intent = new Intent();
                                intent.setClass(LoginActivity.this,
                                        MainActivity.class);
                                dbgUtil.fileLog("user "+m_sName+" offline access @server "+RedAntApplication.active_address);
                                startActivity(intent);
                                finish();
                            }
                            else
                            {
                                // wrong password
                                Toast toast = Toast.makeText(
                                        getApplicationContext(),
                                        getText(R.string.msg_user_wrong),
                                        Toast.LENGTH_LONG);
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();
                                m_etPassword
                                        .setError(getString(R.string.error_incorrect_password));
                                m_etPassword.requestFocus();
                                dbUtil.CloseCursor(cursor);
                                dbUtil.CloseDB(db);
                            }
                        }
                        else*/
                        {// user not exist
                            Toast toast = Toast.makeText(
                                    getApplicationContext(),
                                    getText(R.string.msg_net_error),
                                    Toast.LENGTH_LONG);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            m_etPassword
                                    .setError(null);
                            m_etPassword.requestFocus();
                          /*  dbUtil.CloseCursor(cursor);
                            dbUtil.CloseDB(db);*/

                        }

                        break;
                    }
                    // case Network.RESULT_NET_ERROR:
                    // {
                    // Toast toast = Toast.makeText(getApplicationContext(),
                    // getText(R.string.msg_net_error),
                    // Toast.LENGTH_LONG);
                    // toast.setGravity(Gravity.CENTER, 0, 0);
                    // toast.show();
                    // return;
                    // }
                    case Network.RESULT_FALSE:
                    {
                        Toast toast = Toast.makeText(getApplicationContext(),
                                getText(R.string.msg_user_wrong),
                                Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        m_etPassword
                                .setError(getString(R.string.error_incorrect_password));
                        m_etPassword.requestFocus();
                        return;
                    }

                    default:
                        break;
                }

            }
        }

        @Override
        protected void onCancelled()
        {
            mAuthTask = null;
            showProgress(false);
        }
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show)
    {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
        {
            int shortAnimTime = getResources().getInteger(
                    android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate().setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter()
                    {
                        @Override
                        public void onAnimationEnd(Animator animation)
                        {
                            mLoginStatusView.setVisibility(show ? View.VISIBLE
                                    : View.GONE);
                        }
                    });

//            mLoginFormView.setVisibility(View.VISIBLE);
//            mLoginFormView.animate().setDuration(shortAnimTime)
//                    .alpha(show ? 0 : 1)
//                    .setListener(new AnimatorListenerAdapter()
//                    {
//                        @Override
//                        public void onAnimationEnd(Animator animation)
//                        {
//                            mLoginFormView.setVisibility(show ? View.GONE
//                                    : View.VISIBLE);
//                        }
//                    });
        }
        else
        {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }
    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin()
    {
        if (mAuthTask != null)
        {
            return;
        }

        // Reset errors.
        m_etName.setError(null);
        m_etPassword.setError(null);

        // Store values at the time of the login attempt.
        m_sName = m_etName.getText().toString();
        m_sPassword = m_etPassword.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(m_sPassword))
        {
            m_etPassword.setError(getString(R.string.error_field_required));
            focusView = m_etPassword;
            cancel = true;
        }
        else if (m_sPassword.length() < 4)
        {
            m_etPassword.setError(getString(R.string.error_invalid_password));
            focusView = m_etPassword;
            cancel = true;
        }

        // Check for a valid user name.
        if (TextUtils.isEmpty(m_sName))
        {
            m_etName.setError(getString(R.string.error_field_required));
            focusView = m_etName;
            cancel = true;
        }
        // else if (!m_sName.contains("@")) {
        // m_etName.setError(getString(R.string.error_invalid_email));
        // focusView = m_etName;
        // cancel = true;
        // }

        if (cancel)
        {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        }
        else
        {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            mAuthTask = new FullScreenLoginActivity.UserLoginTask();
            mAuthTask.execute((Void) null);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        String server=data.getStringExtra("server");
        m_etServer.setText(server);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_screen_login);

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }


        TextView tv_ver = (TextView) findViewById(R.id.tv_ver);
        try
        {

            tv_ver.setText(getText(R.string.str_ver)
                    + RedAntApplication.getInstance()
                    .getPackageManager()
                    .getPackageInfo("com.usai.redant.raimage", 0).versionName);
        }
        catch (PackageManager.NameNotFoundException e1)
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        m_etName = (EditText) findViewById(R.id.et_user);
        m_etServer = (EditText) findViewById(R.id.et_server);
        // m_etName.setText(m_sName);

        m_etPassword = (EditText) findViewById(R.id.et_pwd);

        m_swSave = (Switch) findViewById(R.id.sw_save);
        SharedPreferences pref = RedAntApplication.getInstance()
                .getSharedPreferences("RA Image", 0);
        String u = pref.getString("user", null);
        String p = pref.getString("password", null);
        String s = pref.getString("aa", null);
        if (u != null && p != null)
        {
            try
            {
                m_etName.setText(AES.decrypt("usai2010", u));
                m_etPassword.setText(AES.decrypt("usai2010", p));
                m_swSave.setChecked(true);
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        m_etServer.setText(s);

        m_etPassword
                .setOnEditorActionListener(new TextView.OnEditorActionListener()
                {
                    @Override
                    public boolean onEditorAction(TextView textView, int id,
                                                  KeyEvent keyEvent)
                    {
                        if (id == R.id.login
                                || id == EditorInfo.IME_ACTION_DONE)
                        {
                            InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext()
                                    .getSystemService(INPUT_METHOD_SERVICE);

                            // EditText editText =
                            // (EditText)findViewById(R.id.xxxx);
                            inputMethodManager.hideSoftInputFromWindow(
                                    m_etPassword.getWindowToken(), 0); // ����
                            attemptLogin();
                            return true;
                        }
                        return false;
                    }
                });

//        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.bt_login).setOnClickListener(
                new View.OnClickListener()
                {
                    @Override
                    public void onClick(View view)
                    {

                        attemptLogin();
                    }
                });


        findViewById(R.id.bt_server).setOnClickListener(
                new View.OnClickListener()
                {
                    @Override
                    public void onClick(View view)
                    {
                        Intent intent = new Intent();
                        intent.setClass(FullScreenLoginActivity.this,ServerSettingActivity.class);
//                        startActivity(intent);

//                        Intent intent = new Intent(MainActivity.this,
//                                PhotoPreviewActivity.class);
//                        intent.putExtra("pic_list", (Serializable) photoList);
                        startActivityForResult(intent, 0);

                    }
                });


        if(TextUtils.isEmpty(RedAntApplication.station_name))
        {
            Intent intent = new Intent();
            intent.setClass(FullScreenLoginActivity.this,ServerSettingActivity.class);
//            startActivity(intent);
            startActivityForResult(intent, 0);
        }
    }
}
