package com.rthoni.camotion.ui;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.luticate.auth.dbo.LuLoginDbo;
import com.luticate.utils.business.LuPromise;
import com.rthoni.camotion.R;
import com.rthoni.camotion.dbo.LocationDbo;
import com.rthoni.camotion.ui.dialogs.LoginDialog;

public class AddAccountActivity extends AppCompatActivity {

    private EditText _nameInput;
    private EditText _usernameInput;
    private EditText _passwordInput;
    private EditText _domainInput;
    private CheckBox _checkBoxHttps;

    private AccountAuthenticatorResponse _response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_account);
        _nameInput = (EditText) findViewById(R.id.name_input);
        _usernameInput = (EditText) findViewById(R.id.username_input);
        _passwordInput = (EditText) findViewById(R.id.password_input);
        _domainInput = (EditText) findViewById(R.id.domain_input);
        _checkBoxHttps = (CheckBox) findViewById(R.id.checkBoxHttps);

        findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                check();
            }
        });
        findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(Activity.RESULT_CANCELED);
                finish();
            }
        });

        Bundle extras = getIntent().getExtras();

        if (extras != null) {
            _response = extras.getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
        }
    }

    private LocationDbo validate()
    {
        LocationDbo location = new LocationDbo();
        location.setName(_nameInput.getText().toString());
        location.setUsername(_usernameInput.getText().toString());
        location.setPassword(_passwordInput.getText().toString());
        location.setDomain(_domainInput.getText().toString());
        location.setHttps(_checkBoxHttps.isChecked());

        _nameInput.setError(null);
        _usernameInput.setError(null);
        _passwordInput.setError(null);
        _domainInput.setError(null);

        if (location.getName().isEmpty()) {
            _nameInput.setError(getResources().getString(R.string.error_name));
            _nameInput.requestFocus();
            return null;
        }

        if (location.getUsername().isEmpty()) {
            _usernameInput.setError(getResources().getString(R.string.error_username));
            _usernameInput.requestFocus();
            return null;
        }

        if (location.getPassword().isEmpty()) {
            _passwordInput.setError(getResources().getString(R.string.error_password));
            _passwordInput.requestFocus();
            return null;
        }

        if (location.getDomain().isEmpty()) {
            _domainInput.setError(getResources().getString(R.string.error_domain));
            _domainInput.requestFocus();
            return null;
        }

        return location;
    }

    private void addAccount(LocationDbo location)
    {
        String username = location.getPseudoMail();

        AccountManager accountManager = AccountManager.get(this);
        Account newUserAccount = new Account(username, getResources().getString(R.string.account_type));
        boolean accountCreated = accountManager.addAccountExplicitly(newUserAccount, location.getPassword(), null);

        if (accountCreated && _response != null) {
            accountManager.setUserData(newUserAccount, "Https", location.isHttps() ? "true" : "false");
            accountManager.setUserData(newUserAccount, "Domain", location.getDomain());
            Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, username);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, getString(R.string.account_type));
            _response.onResult(result);
            finish();
        }
    }

    private void check()
    {
        final LocationDbo location = validate();
        if (location == null) {
            return;
        }
        LoginDialog dlg = new LoginDialog(this);
        dlg.login(location).then(new LuPromise.LuConsumer<LuLoginDbo>() {
            @Override
            public void execute(LuLoginDbo data) {
                addAccount(location);
            }
        }, new LuPromise.LuConsumer<LuPromise.LuPromiseError>() {
            @Override
            public void execute(LuPromise.LuPromiseError error) {
                Toast.makeText(AddAccountActivity.this, error.toString(), Toast.LENGTH_LONG).show();
            }
        });
    }
}
