package info.knacki.pass.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import info.knacki.pass.R;
import info.knacki.pass.io.FileInterfaceFactory;
import info.knacki.pass.io.IFileInterface;
import info.knacki.gitdroid.callback.OnResponseListener;
import info.knacki.pass.settings.SettingsManager;
import info.knacki.pass.ui.passwordPicker.PasswordPickerFactory;

public class EditPasswordActivity extends AppCompatActivity {
    private static final Logger log = Logger.getLogger(EditPasswordActivity.class.getName());
    public static final String INTENT_PATH = "EditPasswordActivity_PATH";
    public static final String INTENT_EDIT = "EditPasswordActivity_EDIT";
    protected File fOutputFile;
    protected AppCompatEditText fTextEdit;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.editpassword_menu, menu);
        if (SettingsManager.GetVCS(this) == null) {
            // Disable sync option
            menu.removeItem(R.id.id_sync);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.encryption_information) {
            Intent i = new Intent(this, EncryptionInformationActivity.class);
            i.putExtra(EncryptionInformationActivity.FILE_PATH, fOutputFile.getAbsolutePath());
            startActivity(i);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pass_edit);
        String path = getIntent().getStringExtra(INTENT_PATH);
        if (path == null) {
            finish();
            throw new RuntimeException("Error: unset PATH");
        }
        fOutputFile = new File(path);
        fTextEdit = findViewById(R.id.password_edit);
        ((AppCompatCheckBox) findViewById(R.id.showPasswordCheckbox)).setOnCheckedChangeListener((compoundButton, b) -> {
            final int cursorPos = fTextEdit.getSelectionEnd();
            fTextEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE | (compoundButton.isChecked() ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_TEXT_VARIATION_PASSWORD));
            fTextEdit.setSelection(cursorPos);
        });
        findViewById(R.id.saveButton).setOnClickListener(view -> {
            final Editable text = fTextEdit.getText();
            final String textStr = text == null ? "" : text.toString();

            try {
                FileInterfaceFactory.GetFileInterface(EditPasswordActivity.this, PasswordPickerFactory.GetPasswordPicker(EditPasswordActivity.this), fOutputFile).WriteFile(textStr, new OnResponseListener<Void>() {
                    @Override
                    public void OnResponse(Void result) {
                        EditPasswordActivity.this.finish();
                    }

                    @Override
                    public void OnError(final String msg, final Throwable e) {
                        EditPasswordActivity.this.runOnUiThread(() -> {
                            Toast.makeText(EditPasswordActivity.this, "Error: " + msg, Toast.LENGTH_LONG).show();
                            log.log(Level.WARNING, msg, e);
                        });
                    }
                });
            }
            catch (IFileInterface.InvalidPasswordException e) {
                log.log(Level.WARNING, e.getMessage(), e);
                Toast.makeText(EditPasswordActivity.this, "Error: " +e.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        boolean editMode = getIntent().getBooleanExtra(INTENT_EDIT, true);
        populateContent(editMode);
        if (!editMode) {
            ((AppCompatCheckBox) findViewById(R.id.showPasswordCheckbox)).setChecked(true);
        }
    }

    protected void populateContent(final boolean requestFocus) {
        fTextEdit.setEnabled(false);
        FileInterfaceFactory.GetFileInterface(this, PasswordPickerFactory.GetPasswordPicker(this), fOutputFile).ReadFile(new OnResponseListener<String>() {
            @Override
            public void OnResponse(final String pass) {
                EditPasswordActivity.this.runOnUiThread(() -> {
                    fTextEdit.setEnabled(true);
                    fTextEdit.setText(pass);
                    if (requestFocus) {
                        fTextEdit.setSelection(pass.length());
                        fTextEdit.requestFocus();
                    }
                });
            }

            @Override
            public void OnError(final String msg, final Throwable e) {
                EditPasswordActivity.this.runOnUiThread(() -> {
                    Toast.makeText(EditPasswordActivity.this, "Error: " +msg, Toast.LENGTH_LONG).show();
                    log.log(Level.WARNING, msg, e);
                    finish();
                });
            }
        });
    }
}
