package info.knacki.pass.io.pgp;

import android.content.Context;
import android.content.res.Resources;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import info.knacki.pass.R;
import info.knacki.pass.io.CharsetHelper;
import info.knacki.pass.io.FileInterfaceFactory;
import info.knacki.pass.io.IFileInterface;
import info.knacki.gitdroid.callback.OnResponseListener;

public class GPGFileInterface implements IFileInterface {
    private final File fFile;
    private final FileInterfaceFactory.PasswordGetter fPasswordGetter;
    private final Context fContext;

    public GPGFileInterface(Context ctx, FileInterfaceFactory.PasswordGetter passwordGetter, File f) {
        fFile = f;
        fPasswordGetter = passwordGetter;
        fContext = ctx;
    }

    @Override
    public void ReadFile(final OnResponseListener<String> resp) {
        if (fFile.length() == 0) {
            resp.OnResponse("");
            return;
        }
        try {
            if (!GPGStorageEngine.GetDefaultEngine(fContext).HasGPGKey())
                throw new FileNotFoundException("GPG key not set");
            GPGUtil.DecryptFile(fContext, fPasswordGetter, fFile, new OnResponseListener<byte[]>() {
                @Override
                public void OnResponse(byte[] result) {
                    resp.OnResponse(CharsetHelper.ByteArrayToString(result));
                }

                @Override
                public void OnError(String msg, Throwable e) {
                    resp.OnError(msg, e);
                }
            });
        } catch (Throwable e) {
            resp.OnError(e.getMessage(), e);
        }
    }

    @Override
    public void WriteFile(String content, OnResponseListener<Void> resp) {
        try {
            if (!GPGStorageEngine.GetDefaultEngine(fContext).HasGPGKey())
                throw new FileNotFoundException("GPG key not set");
            GPGUtil.CryptFile(fContext, new FileOutputStream(fFile), CharsetHelper.StringToByteArray(content), resp);
        }
        catch (Throwable e) {
            resp.OnError(e.getMessage(), e);
        }
    }

    @Override
    public String GetMethodName() {
        Resources r = fContext.getResources();
        String details;
        if (GPGStorageEngine.GetDefaultEngine(fContext).HasGPGKey()) {
            try {
                details = r.getString(GPGUtil.CheckIsPasswordProtected(fContext) ? R.string.protected_key : R.string.unprotected_key_short);
            } catch (IOException e) {
                details = e.getMessage();
            }
        } else {
            details = r.getString(R.string.unset_gpg_key);
        }
        return r.getString(R.string.pref_enc_type_title_gpg) +" (" +details +")";
    }
}
