package org.mercury_im.messenger.android.ui.account.login;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import org.bouncycastle.openpgp.PGPException;
import org.mercury_im.messenger.R;

import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

public class IkeyBackupRestoreOrSkipFragment extends Fragment {

    @BindView(R.id.btn_restore)
    Button restoreButton;

    @BindView(R.id.btn_new_key)
    Button regenerateButton;

    @BindView(R.id.edit_backup_code)
    EditText backupCodeEditText;

    @BindView(R.id.btn_scan)
    ImageButton scanButton;

    private final UUID accountId;

    private AndroidIkeySetupViewModel viewModel;

    IkeyBackupRestoreOrSkipFragment(UUID accountId) {
        this.accountId = accountId;
    }

    public static IkeyBackupRestoreOrSkipFragment newInstance(UUID accountId) {
        return new IkeyBackupRestoreOrSkipFragment(accountId);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ikey_backup_restore, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(requireActivity()).get(AndroidIkeySetupViewModel.class);

        restoreButton.setOnClickListener(v -> onRestore());
        regenerateButton.setOnClickListener(v -> {
            try {
                viewModel.generateIdentityKey();
            } catch (PGPException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchProviderException e) {
                e.printStackTrace();
            } catch (InvalidAlgorithmParameterException e) {
                e.printStackTrace();
            }
            ((IkeySetupNavigator) getActivity()).displayInfo(accountId);
        });

        viewModel.getPassphraseError().observe(this, opt -> {
            if (opt.isPresent()) {
                Toast.makeText(getContext(), opt.getItem(), Toast.LENGTH_SHORT).show();
            }
        });
        scanButton.setOnClickListener(v -> startQrCodeScanIntent());
    }

    public void onRestore() {
        String backupCode = backupCodeEditText.getText().toString();

        if (viewModel.restoreBackup(backupCode)) {
            ((IkeySetupNavigator) getActivity()).restoreSuccessful(accountId);
        }

    }

    public void startQrCodeScanIntent() {
        try {

            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
            intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes

            startActivityForResult(intent, 0);

        } catch (Exception e) {

            Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
            Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
            startActivity(marketIntent);

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {

            if (resultCode == RESULT_OK) {
                String contents = data.getStringExtra("SCAN_RESULT");
                backupCodeEditText.setText(contents);
            }
            if(resultCode == RESULT_CANCELED){
                //handle cancel
            }
        }
    }
}
