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

import androidx.lifecycle.ViewModelProvider;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;

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

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.mercury_im.messenger.R;
import org.mercury_im.messenger.android.crypto.ikey.AndroidIkeyBackupCreationViewModel;

import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

public class IkeyBackupCreationFragment extends Fragment {

    private AndroidIkeyBackupCreationViewModel viewModel;

    @BindView(R.id.backup_code)
    TextView backupCode;

    @BindView(R.id.qr_code)
    ImageView qrCode;

    @BindView(R.id.btn_done)
    Button doneButton;

    private final UUID accountId;

    private IkeyBackupCreationFragment(UUID accountId) {
        this.accountId = accountId;
    }

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

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

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(AndroidIkeyBackupCreationViewModel.class);
        viewModel.initialize(accountId);

        viewModel.uploadBackup();

        viewModel.getPassphrase().observe(getViewLifecycleOwner(), passphrase -> backupCode.setText(passphrase));
        viewModel.getPassphraseAsQrCode().observe(getViewLifecycleOwner(), bitmap -> qrCode.setImageBitmap(bitmap));
        doneButton.setOnClickListener(v -> getActivity().finish());

        ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);

        backupCode.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipData clip = ClipData.newPlainText(backupCode.getText(), backupCode.getText());
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getContext(), "Copied to clipboard", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

}
