package flag.android.ctf.com.myapplication;

import android.view.KeyEvent;
import android.view.View;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import cn.pedant.SweetAlert.SweetAlertDialog;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {
    private final Integer SECONDS = 1000;
    private final String TOTALLY_NOT_A_PASSWORD_TRUST_ME = "[3co356a;1&"; //  [3co356a;1&
    private SweetAlertDialog mDialog;
    private String mFlag;
    private Handler mHandler;
    private EditText mPasswordView;
    private FloatingActionButton mSubmitButton;


    private void attemptLogin() {
        mPasswordView.setError(null);
        String password = mPasswordView.getText().toString();

        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.mandatory_field));
        }
        if (!isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.invalid_password));
            return;
        }

        loginUser(password);
    }

    private String generateFlag() throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(TOTALLY_NOT_A_PASSWORD_TRUST_ME.getBytes());
        String flag = String.format("%032X", new BigInteger(1, messageDigest.digest()));

        return flag.substring(0, Math.min(flag.length(), 6));
    }

    private boolean isPasswordValid(String password) {
        return  password.length() >= 4;
    }

    private void loginUser(final String password) {
        mDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        mDialog.getProgressHelper().setBarColor(Color.parseColor("#9FC967"));
        mDialog.setTitleText("Logging in...");
        mDialog.setCancelable(false);
        mDialog.show();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mDialog.setCancelable(true);
                if ( TOTALLY_NOT_A_PASSWORD_TRUST_ME.equals(password)) {
                    String msg = String.format("Flag : KYN2016_%s", mFlag);
                    mDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                    mDialog.setTitleText(msg);
                } else {
                    String msg = "The password is incorrect!";
                    mDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE);
                    mDialog.setTitleText(msg);
                }

            }
        }, 5 * SECONDS);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_main);
        mHandler = new Handler();

        try {
            mFlag = generateFlag();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        mPasswordView = (EditText)findViewById(R.id.edit_password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.edit_password || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        mSubmitButton = (FloatingActionButton) findViewById(R.id.button_submit);
        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptLogin();
            }
        });
    }
}
