package com.example.maliciousapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class HashfileActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hashfile);


            Log.d("MOBIOTSEC", "Activity called..");

            Intent intent = getIntent();
            String filePath = intent.getData().getEncodedPath();

            // calculate hash
            String hash = calcHash(filePath);

            // return the hash in a "result" intent
            Intent resultIntent = new Intent();
            resultIntent.putExtra("hash", hash);
            setResult(Activity.RESULT_OK, resultIntent);
            finish();

            Log.d("MOBIOTSEC", "Activity finished..");
    }

    public String calcHash(String filePath) {

        if (this.isStoragePermissionGranted()) {

            File file = new File(filePath);
            int size = (int) file.length();
            byte[] bytes = new byte[size];
            try {
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
                buf.read(bytes, 0, bytes.length);
                buf.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return DigestUtils.sha256Hex(bytes);
        }
        else
            return "";
    }


    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {

            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.d("MOBIOTSEC", "Permission is granted");
                return true;
            } else {

                Log.d("MOBIOTSEC", "Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else { //permission is automatically granted on sdk<23 upon installation
            Log.d("MOBIOTSEC", "Permission is granted");
            return true;
        }
    }

}