package info.knacki.pass.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.AppCompatTextView;
import android.view.MenuItem;
import android.widget.RadioGroup;

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

import info.knacki.pass.R;
import info.knacki.pass.io.FileInterfaceFactory;
import info.knacki.pass.io.FileMigratoryUtils;
import info.knacki.pass.io.FileUtils;
import info.knacki.pass.io.IFileInterface;
import info.knacki.gitdroid.callback.OnResponseListener;
import info.knacki.pass.settings.SettingsManager;
import info.knacki.pass.ui.alertPrompt.AlertPromptGenerator;
import info.knacki.pass.ui.alertPrompt.views.TextView;
import info.knacki.pass.ui.passwordPicker.PasswordPickerFactory;

public class EncryptionInformationActivity extends AppCompatActivity {
    public static final String FILE_PATH = EncryptionInformationActivity.class.getName() +"FILE_PATH";
    private static final Logger log = Logger.getLogger(EncryptionInformationActivity.class.getName());
    private File fEncrypted;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String filePath = getIntent().getStringExtra(FILE_PATH);
        if (filePath == null) {
            finish();
            return;
        }
        fEncrypted = new File(filePath);
        setContentView(R.layout.activity_encryption_infos);

        findViewById(R.id.change_encryption_method).setOnClickListener((v) -> {
            RadioGroup radioGroup = new RadioGroup(EncryptionInformationActivity.this);
            final SettingsManager.EncryptionType prevEncType = FileInterfaceFactory.GetEncryptionType(fEncrypted);

            for (Map.Entry<SettingsManager.EncryptionType, String> enc: FileInterfaceFactory.GetEncryptionMethodNames(getResources())) {
                AppCompatRadioButton radioButton = new AppCompatRadioButton(this);
                radioButton.setId(enc.getKey().IntValue());
                radioButton.setText(enc.getValue());
                radioGroup.addView(radioButton);
                if (prevEncType.equals(enc.getKey()))
                    radioGroup.check(radioButton.getId());
            }
            AlertPromptGenerator.StaticMake(EncryptionInformationActivity.this)
                    .setView(radioGroup)
                    .setNegativeButton(R.string.cancel, null)
                    .setPositiveButton(R.string.change, (dialogInterface, view) -> {
                        if (radioGroup.getCheckedRadioButtonId() != prevEncType.IntValue()) {
                            String path = fEncrypted.getAbsolutePath();
                            final String previousExtension = FileInterfaceFactory.GetExtension(prevEncType);
                            final SettingsManager.EncryptionType newEncType = SettingsManager.EncryptionType.FromInt(radioGroup.getCheckedRadioButtonId());
                            if (path.endsWith(previousExtension))
                                path = path.substring(0, path.length() -previousExtension.length());
                            path += FileInterfaceFactory.GetExtension(newEncType);
                            File fileTo = new File(path);
                            log.info("Migrating from " +fEncrypted.getAbsolutePath() +" to " +path);
                            FileMigratoryUtils.MigratePassword(EncryptionInformationActivity.this, fEncrypted, fileTo, PasswordPickerFactory.GetPasswordPicker(EncryptionInformationActivity.this), new OnResponseListener<Void>() {
                                @Override
                                public void OnResponse(Void result) {
                                    fEncrypted = fileTo;
                                    FillView();
                                }

                                @Override
                                public void OnError(String msg, Throwable e) {

                                }
                            }, true);
                        }
                    })
                    .setTitle(R.string.change_encryption_method)
                    .show();
        });
        findViewById(R.id.remove).setOnClickListener(view -> AlertPromptGenerator.StaticMake(this)
                    .setTitle(R.string.are_you_sure)
                    .setView(new TextView(this).SetText(String.format(getString(R.string.about_to_rm_file), fEncrypted.getName())))
                    .setPositiveButton(R.string.ok, (dialogInterface, v) -> {
                        FileUtils.TrashFile(fEncrypted);
                        EncryptionInformationActivity.this.finish();
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show());
        FillView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void FillView() {
        setTitle(FileUtils.TrimExtension(fEncrypted.getName()));
        IFileInterface f = FileInterfaceFactory.GetFileInterface(this, null, fEncrypted);
        ((AppCompatTextView) findViewById(R.id.filepath)).setText(fEncrypted.getName());
        ((AppCompatTextView) findViewById(R.id.enc_method)).setText(f.GetMethodName());
    }
}
