package guard.api.sensitive.ui.sapiguard.components;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import guard.api.sensitive.ui.sapiguard.IPackageService;
import guard.api.sensitive.ui.sapiguard.PackageService;
import guard.api.sensitive.ui.sapiguard.SensitiveApiRecord;
import guard.api.sensitive.ui.sapiguard.utils.Util;

public class PkgChange extends BroadcastReceiver {
    public static  String DB_EXTRACTED = "android.intent.action.DB_EXTRACTED";
    public static  String TESTING = "android.intent.action.TESTING";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            if (intent.hasExtra("hookpkg")){
                String pkgname = intent.getStringExtra("hookpkg");
                IPackageService client = PackageService.getClient();
                if (client != null){
                    client.clear();
                    client.setPkgName(pkgname);

                    File screenshotDir = new File(Environment.getExternalStorageDirectory() + File.separator +"sapiguardSS");
                    if (screenshotDir.exists() && screenshotDir.isDirectory())
                        deleteFolder(screenshotDir);
                    screenshotDir.mkdir();
                }
            }

            if (intent.getAction()!= null){
                if (intent.getAction().equals(DB_EXTRACTED)) {
                    List<SensitiveApiRecord> arrayList = PackageService.getClient().readDBContent();
//                    Log.d("jie-onReceive", arrayList.toString());
                    copyDBtoExternalStorage(arrayList);
                    List<String> recordList = PackageService.getClient().readRecordConent();

                    copyRecordtoExternalStorage(recordList);
                }else if (intent.getAction().equals(TESTING)){
                    List<SensitiveApiRecord> arrayList = PackageService.getClient().readDBContent();
                    Log.d("jie-TESTING", arrayList.toString());

                }
            }

        } catch (Throwable ex) {
            ex.printStackTrace();
        }

    }

    private void deleteFolder(File folder) {
        File[] files = folder.listFiles();
        if(files!=null) { //some JVMs return null for empty dirs
            for(File f: files) {
                if(f.isDirectory()) {
                    deleteFolder(f);
                } else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }

    private void copyDBtoExternalStorage(List<SensitiveApiRecord> recordList) {
        Log.d("jie-copy1", "copyDBtoExternalStorage");

        try {
            File dbFile = new File(Environment.getExternalStorageDirectory() + File.separator + "sapiguard" + File.separator + "sapiguard.db");
            dbFile.getParentFile().mkdirs();
            dbFile.delete();
            dbFile.createNewFile();

            if (!dbFile.exists())
                return;
            ReentrantReadWriteLock mLock = new ReentrantReadWriteLock(true);
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);

            mLock.writeLock().lock();
            try {
                db.beginTransaction();
                try {
                    db.execSQL("CREATE TABLE IF NOT EXISTS apitrace (id INTEGER primary key autoincrement, stacktrace TEXT NOT NULL, hascode INTEGER  NOT NULL, mtdsig TEXT NOT NULL, times INTEGER NOT NULL, topaty TEXT)");
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
            } finally {
                mLock.writeLock().unlock();
            }


            mLock.writeLock().lock();
            try {
                db.beginTransaction();
                try {
                    for (SensitiveApiRecord record : recordList) {
                        ContentValues values = new ContentValues();
                        values.put("id", record.id);
                        values.put("stacktrace", record.stacktrace);
                        values.put("hascode", record.hascode);
                        values.put("mtdsig", record.mtdsig);
                        values.put("times", record.times);
                        values.put("topaty", record.topAty);

                        db.insertWithOnConflict("apitrace", null, values,
                                SQLiteDatabase.CONFLICT_REPLACE);
                    }
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
            } finally {
                mLock.writeLock().unlock();
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    private void copyRecordtoExternalStorage(List<String> recordList) {
        Log.d("jie-copy1", "copyRecordtoExternalStorage");

        try {

            File recordFile = new File(Environment.getExternalStorageDirectory() + File.separator + "sapiguardSS" + File.separator + "record.txt");
            recordFile.getParentFile().mkdirs();
            recordFile.delete();
            recordFile.createNewFile();

            if (!recordFile.exists())
                return;

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(
                    recordFile, true));
            for(String record : recordList){
                outputStreamWriter.write(record);
                outputStreamWriter.write("\n");
            }
            outputStreamWriter.close();
        } catch (Throwable exex) {
            Util.bug(null, exex);
        }
    }
}
