package com.utopiaindustries.qualitychecker.ui.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.utopiaindustries.qualitychecker.R;
import com.utopiaindustries.qualitychecker.apiservice.ApiService;
import com.utopiaindustries.qualitychecker.apiservice.ApiServiceFactory;
import com.utopiaindustries.qualitychecker.apiservice.GiteaClient;
import com.utopiaindustries.qualitychecker.apiservice.GiteaRestService;
import com.utopiaindustries.qualitychecker.db.CheckpointRepository;
import com.utopiaindustries.qualitychecker.db.DefectRepository;
import com.utopiaindustries.qualitychecker.db.DimensionRepository;
import com.utopiaindustries.qualitychecker.db.InspectionCheckpointSkuRepository;
import com.utopiaindustries.qualitychecker.db.InspectionLabelRepository;
import com.utopiaindustries.qualitychecker.db.ItemRepository;
import com.utopiaindustries.qualitychecker.db.ProductRepository;
import com.utopiaindustries.qualitychecker.db.ReportRepository;
import com.utopiaindustries.qualitychecker.models.EmployeePhoto;
import com.utopiaindustries.qualitychecker.models.InspectionReport;
import com.utopiaindustries.qualitychecker.models.InspectionReportWrapper;
import com.utopiaindustries.qualitychecker.models.callback.SaveCheckpointCallback;
import com.utopiaindustries.qualitychecker.models.callback.SaveDefectCallback;
import com.utopiaindustries.qualitychecker.models.callback.SaveDimensionCallback;
import com.utopiaindustries.qualitychecker.models.callback.SaveInspectionLabelCallBack;
import com.utopiaindustries.qualitychecker.models.callback.SaveItemCallback;
import com.utopiaindustries.qualitychecker.models.callback.SaveProductCallBack;
import com.utopiaindustries.qualitychecker.models.callback.SaveReportCallback;
import com.utopiaindustries.qualitychecker.notification.NotificationHelper;
import com.utopiaindustries.qualitychecker.receiver.NetworkReceiver;
import com.utopiaindustries.qualitychecker.service.InspectionReportService;
import com.utopiaindustries.qualitychecker.service.NetworkService;
import com.utopiaindustries.qualitychecker.store.Store;
import com.utopiaindustries.qualitychecker.ui.activities.fragments.ReportsFragment;
import com.utopiaindustries.qualitychecker.ui.adapter.PagerAdapter;
import com.utopiaindustries.qualitychecker.ui.adapter.ReportAdapter;
import com.utopiaindustries.qualitychecker.ui.fragments.FirstStepFragment;
import com.utopiaindustries.qualitychecker.utils.FileUtils;
import com.utopiaindustries.qualitychecker.utils.PropertyReader;
import com.utopiaindustries.qualitychecker.utils.Release;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

    private Button createReportBtn,refreshReportsBtn,logoutBtn,fetchProductBtn, appUpdateBtn, reportsUploadBtn;
    //private RecyclerView recyclerView;
    private ApiService apiService;
    private TextView usernameTitle;//, emptyReportTextView;
    private ImageView profileImage;
    private Store store;
    private InspectionReportService inspectionReportService;
    private NetworkReceiver networkReceiver;
    private boolean isReceiverRegistered = false;
    private ProgressBar progressBar;

    TabLayout tabLayout;
    ViewPager viewPager;

    PagerAdapter pagerAdapter;
    private String currentVersionName;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        if( ! isNetworkConnected() ){
            Toast.makeText( this, "No Internet Connection", Toast.LENGTH_LONG ).show();
        }
        setContentView(R.layout.activity_home);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );

        // initialize views
        store = Store.getInstance();
        apiService = ApiServiceFactory.getApiService();
        inspectionReportService = InspectionReportService.getInstance();
        createReportBtn = findViewById( R.id.create_report_btn );
        refreshReportsBtn = findViewById( R.id.refresh_btn );
        logoutBtn = findViewById( R.id.logout_btn );
        fetchProductBtn = findViewById( R.id.fetch_product_btn );
        appUpdateBtn = findViewById(R.id.app_update_btn);
        reportsUploadBtn = findViewById(R.id.reports_upload_btn);
        progressBar = findViewById(R.id.progressBar);
        //recyclerView = findViewById( R.id.reports_recyclerview );
        usernameTitle = findViewById( R.id.username_title );
        profileImage = findViewById( R.id.profile_image );
        //emptyReportTextView = findViewById( R.id.empty_report_text );

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        pagerAdapter = new PagerAdapter(getSupportFragmentManager(), HomeActivity.this);
        viewPager.setAdapter(pagerAdapter);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);

        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }

        refreshReportsBtn.setOnClickListener( this );
        createReportBtn.setOnClickListener( this );
        logoutBtn.setOnClickListener( this );
        fetchProductBtn.setOnClickListener( this );
        appUpdateBtn.setOnClickListener( this );
        reportsUploadBtn.setOnClickListener( this );

        //recyclerView.setLayoutManager( new LinearLayoutManager( this ) );

        updateProfileImage();
      //  refreshReportData();
    }

    /*private void refreshReportData(){
        SharedPreferences sharedPreferences = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        String username = sharedPreferences.getString("username", null );
        apiService.fetchAllReports( username ).enqueue(
                new Callback<List<InspectionReport>>() {
                    @Override
                    public void onResponse(Call<List<InspectionReport>> call, Response<List<InspectionReport>> response) {
                        if( response.isSuccessful() && response.body() != null ){
                            System.out.println( response.body() );
                            ReportAdapter adapter = new ReportAdapter( response.body() );
                            recyclerView.setAdapter( adapter );
                            if( response.body().isEmpty() )
                                emptyReportTextView.setVisibility( View.VISIBLE ) ;
                        } else {
                            System.out.println("Error");
                            emptyReportTextView.setVisibility( View.VISIBLE ) ;
                        }
                    }
                    @Override
                    public void onFailure(Call<List<InspectionReport>> call, Throwable t) {
                        System.out.println( t.getMessage() );
                        emptyReportTextView.setVisibility( View.VISIBLE ) ;
                    }
                }
        );
    }*/

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if( id == R.id.create_report_btn ){
            SharedPreferences sharedPreferences = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.putString("draftReportId", "0");
            editor.apply();

            Intent intent = new Intent( this, MainActivity.class );
            intent.putExtra("fromClass", "Home");
            intent.putExtra("draftID", "0");
            startActivity( intent );
        }
        if( id == R.id.logout_btn ){
            SharedPreferences sharedPreferences = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("username", null );
            editor.putString("password", null );
            editor.apply();
            Intent intent = new Intent( HomeActivity.this, LoginActivity.class );
            startActivity( intent );
            finish();
        }
        if( id == R.id.refresh_btn ){
          //  refreshReportData();
            updateProfileImage();
            ReportsFragment secondFragment = (ReportsFragment) getSupportFragmentManager().getFragments().get(0);
            secondFragment.updateData();

        }
        if( id == R.id.fetch_product_btn ){
            if( isNetworkConnected() ) {
                fetchAndPopulateProductData();
                fetchAndPopulateDimensionsData();
                fetchAndPopulateCheckpointData();
                fetchAndPopulateDefectsData();
                fetchAndPopulateUnitsData();
                fetchAndPopulateSkuCheckpointsData();
                fetchAndPopulateInspectionLevelData();
            } else {
                Toast.makeText( this, "network not available", Toast.LENGTH_LONG ).show();
            }
        }

        if ( id == R.id.app_update_btn) {

            if (!FileUtils.isNetworkConnected(this)) {
                Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG).show();
            }
            else {
                checkForUpdates();
            }

        }

        if ( id == R.id.reports_upload_btn) {

            if (!FileUtils.isNetworkConnected(this)) {
                Toast.makeText(this, "No Internet Connection Available", Toast.LENGTH_LONG).show();
            }
            else {
                pushDataToInternet();
            }

        }
    }

private int generateRandomNumber(int min, int max) {
    return (int) (Math.random() * ((max - min) + 1)) + min;
}

    private void updateProfileImage(){
        SharedPreferences sharedPreferences = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", null );
        if( username != null ){
            apiService.fetchEmployeePhoto( username ).enqueue(
                    new Callback<EmployeePhoto>() {
                        @Override
                        public void onResponse(Call<EmployeePhoto> call, Response<EmployeePhoto> response) {
                            System.out.println( response.body() );
                            if( response.isSuccessful() && response.body() != null ){
                                System.out.println( response.body() );
                                editor.putString("name" , response.body().getName() );
                                editor.apply();
                                usernameTitle.setText( response.body().getName() );
                                store.setEmployeePhoto( response.body() );
                                //Log.e("Profile-Image: ",""+store.getProfileImage());
                                Glide.with( getBaseContext() )
                                        .load( store.getProfileImage( ) )
                                        .into( profileImage );
                            }
                        }

                        @Override
                        public void onFailure(Call<EmployeePhoto> call, Throwable t) {
                            System.out.println( t.getMessage() );
                            String name = sharedPreferences.getString("name", null);
                            usernameTitle.setText( name );
                        }
                    }
            );

        }
    }


    /*
    *  fetch and update product map
    * */
    private void fetchAndPopulateProductData(){

        NotificationHelper.showProductNotification(
                this,
                "Utopia QA App",
                "Fetching Product Details.");
        inspectionReportService.fetchAndPopulateProducts( new SaveProductCallBack() {
            @Override
            public void onSuccess() {
                Toast.makeText( HomeActivity.this, "Products successfully synced", Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Products successfully synced");
            }

            @Override
            public void onFailure(Throwable throwable) {
                Toast.makeText( HomeActivity.this, "Error in Products syncing " + throwable.getMessage(), Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Error in Products syncing" );
            }
        }, new ProductRepository( this )  );
    }

    /*
     *  fetch and update inspection label
     * */
    private void fetchAndPopulateInspectionLevelData() {

        NotificationHelper.showProductNotification(
                this,
                "Utopia QA App",
                "Fetching Inspection Label.");
        inspectionReportService.fetchAndPopulateInspectionLabel( new SaveInspectionLabelCallBack() {
            @Override
            public void onSuccess() {
                Toast.makeText( HomeActivity.this, "Inspection Labels successfully synced", Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Inspection Labels successfully synced");
            }

            @Override
            public void onFailure(Throwable throwable) {
                Toast.makeText( HomeActivity.this, "Error in Inspection Labels syncing " + throwable.getMessage(), Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Error in Inspection Labels syncing" );
            }
        }, new InspectionLabelRepository( this )  );
    }

    private void fetchAndPopulateDimensionsData(){

        NotificationHelper.showProductNotification( this,
                "Utopia QA App",
                "Fetching Dimensions Details.");
        inspectionReportService.fetchAndPopulateDimensions( new SaveDimensionCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText( HomeActivity.this, "Dimensions successfully synced", Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Dimensions successfully synced");
            }

            @Override
            public void onFailure(Throwable throwable) {
                Toast.makeText( HomeActivity.this, "Error in Dimensions syncing " + throwable.getMessage(), Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Error in Dimensions syncing" );
            }
        }, new DimensionRepository( this )  );
    }

    private void fetchAndPopulateCheckpointData(){

        NotificationHelper.showProductNotification(
                this,
                "Utopia QA App",
                "Fetching Checkpoints Details.");
        inspectionReportService.fetchAndPopulateCheckpoints( new SaveCheckpointCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText( HomeActivity.this, "Checkpoints successfully synced", Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification( HomeActivity.this,
                        "Utopia QA App",
                        "Checkpoints successfully synced");
            }

            @Override
            public void onFailure(Throwable throwable) {
                Toast.makeText( HomeActivity.this, "Error in Checkpoints syncing " + throwable.getMessage(), Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Error in Checkpoints syncing" );
            }
        }, new CheckpointRepository( this )  );
    }

    private void fetchAndPopulateDefectsData(){

        NotificationHelper.showProductNotification(
                this,
                "Utopia QA App",
                "Fetching Defects Details.");
        inspectionReportService.fetchAndPopulateDefects( new SaveDefectCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText( HomeActivity.this, "Defects successfully synced", Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Defects successfully synced");
            }

            @Override
            public void onFailure(Throwable throwable) {
                Toast.makeText( HomeActivity.this, "Error in Defects syncing " + throwable.getMessage(), Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Error in Defects syncing" );
            }
        }, new DefectRepository( this )  );
    }

    private void fetchAndPopulateUnitsData(){

        NotificationHelper.showProductNotification(
                this,
                "Utopia QA App",
                "Fetching Units Details.");
        inspectionReportService.fetchAndPopulateUnits( new SaveItemCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText( HomeActivity.this, "Units successfully synced", Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Units successfully synced");
            }

            @Override
            public void onFailure(Throwable throwable) {
                Toast.makeText( HomeActivity.this, "Error in Units syncing " + throwable.getMessage(), Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Error in Units syncing" );
            }
        }, new ItemRepository( this )  );
    }

    private void fetchAndPopulateSkuCheckpointsData(){

        NotificationHelper.showProductNotification(
                this,
                "Utopia QA App",
                "Fetching sku checkpoints Details.");
        inspectionReportService.fetchAndPopulateSkuCheckpoints( new SaveItemCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText( HomeActivity.this, "Sku Cps successfully synced", Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Sku Cps successfully synced");
            }

            @Override
            public void onFailure(Throwable throwable) {
                Toast.makeText( HomeActivity.this, "Error in Sku Cps  syncing " + throwable.getMessage(), Toast.LENGTH_LONG ).show();
                NotificationHelper.showProductNotification(
                        HomeActivity.this,
                        "Utopia QA App",
                        "Error in Sku Cps " );
            }
        }, new InspectionCheckpointSkuRepository( this )  );
    }



    private boolean isNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    @Override
    protected void onResume() {
        super.onResume();
      //  refreshReportData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        /*if (networkReceiver == null) {
            networkReceiver = new NetworkReceiver();
        }
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkReceiver, filter);
        isReceiverRegistered = true; */ // Mark the receiver as registered
    }

    @Override
    protected void onStop() {
        super.onStop();
        /*if (isReceiverRegistered) {
            unregisterReceiver(networkReceiver);
            isReceiverRegistered = false;  // Mark the receiver as unregistered
        }*/
    }

    /**
     * check for updates
     */
    private void checkForUpdates() {
        Log.e("checkForUpdates: ","*****");
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo( getPackageName(), 0 );
            currentVersionName = info.versionName;
            Log.e("currentVersionName: ",""+currentVersionName);

        } catch ( Exception e ) {
            Log.e("Version-Exception: ",""+e.getMessage());
            e.printStackTrace();
        }
        // adjust views
        progressBar.setVisibility( View.VISIBLE );
        // get properties
        Properties properties = PropertyReader.getProperties( HomeActivity.this );
        String token = properties.getProperty( "gitea_access_token" );
        // send request
        GiteaRestService restService = GiteaClient.getInstance().create( GiteaRestService.class );
        Call<Release> call = restService.getLatestRelease( token );
        call.enqueue( new Callback<Release>() {
            @Override
            public void onResponse( Call<Release> call, Response<Release> response ) {
                Log.e("Response: ",""+response.body());
                if ( response.body() != null ) {
                    Release release = response.body();
                    try {
                        float releaseVersion = Float.parseFloat( release.getName().replace( "v", "" ) );
                        float currentVersion = Float.parseFloat( currentVersionName.replace( "v", "" ) );
                        if ( releaseVersion > currentVersion && !FileUtils.isNullOrEmpty( release.getDownloadUrl() ) ) {
                            String msg = String.format( "Updating to version %s", release.getName() );
                            Toast.makeText( HomeActivity.this, msg, Toast.LENGTH_LONG ).show();
                            Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( release.getDownloadUrl() ) );
                            startActivity( intent );
                            //startApkDownloadAndPerformUpdate( release.getDownloadUrl(), release.getName() );
                        } else {
                            Toast.makeText( HomeActivity.this, "Latest version is already installed", Toast.LENGTH_LONG ).show();
                        }
                    } catch ( Exception e ) {
                        Log.e("Response-Exception: ",""+e.getMessage());
                        Toast.makeText( HomeActivity.this, e.getMessage(), Toast.LENGTH_LONG ).show();
                        e.printStackTrace();
                    }
                }
                progressBar.setVisibility( View.INVISIBLE );
            }

            @Override
            public void onFailure( Call<Release> call, Throwable t ) {
                progressBar.setVisibility( View.INVISIBLE );
                Log.e("Failure: ",""+t.getMessage());
                t.printStackTrace();
            }
        } );
    }

    @SuppressLint("DefaultLocale")
    private void pushDataToInternet() {
        ReportRepository repository = new ReportRepository( this );
        List<InspectionReportWrapper> reportWrappers = repository.findAllUnsynced();
        InspectionReportService service = InspectionReportService.getInstance();
        try {
            List<InspectionReport> reports = getReports( reportWrappers );
            int size = reports.size();
            if( size > 0 ) {
                Toast.makeText(this, "Uploading Reports. Please wait", Toast.LENGTH_LONG).show();
                reportsUploadBtn.setEnabled(false);
                final int[] uploadedCount = {0};

                for ( InspectionReport report : reports ) {
                    service.saveReport(report, new SaveReportCallback() {
                        @Override
                        public void onSuccess() {
                            // update status
                            repository.updateSyncStatus(  report.getWrapperId() );
                            // remove file
                            FileUtils.deleteFile( report.getFilePath() );

                            uploadedCount[0]++;

                            NotificationHelper.showNotification(
                                    HomeActivity.this,
                                    "Report Uploading",
                                    "Uploaded " + uploadedCount[0] + " of " + size + " reports");

                            //Log.e("Reports-size: ",""+reports.size());
                            if (uploadedCount[0] == size) {
                                Toast.makeText(HomeActivity.this, "All reports uploaded successfully", Toast.LENGTH_SHORT).show();
                                reportsUploadBtn.setEnabled(true);
                            }
                        }
                        @Override
                        public void onFailure(Throwable throwable) {
                            Log.e("Message: ",""+throwable.getMessage());
                            uploadedCount[0]++;
                            // Even on failure, increment the counter to avoid locking the button forever
                            //logErrorToFile(throwable);
                            NotificationHelper.showNotification(
                                    HomeActivity.this,
                                    "Report Uploading",
                                    "Uploaded " + uploadedCount[0] + " of " + size + " reports (with some errors)");


                            if (uploadedCount[0] == size) {
                                reportsUploadBtn.setEnabled(true);
                                Toast.makeText(HomeActivity.this, "Finished uploading with some errors", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
            else {
                Toast.makeText(this, "No Reports to upload", Toast.LENGTH_SHORT).show();
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    /*
     * map wrapper to reports
     * */
    private List<InspectionReport> getReports(List<InspectionReportWrapper> wrappers ) {
        List<InspectionReport> reports = new ArrayList<>();
        if( ! wrappers.isEmpty() ){
            for( InspectionReportWrapper wrapper : wrappers ){
                try {
                    // get file from path
                    byte[] result = FileUtils.readFile( wrapper.getContent() );
                    /*FileUtils.copyFile(this, wrapper.getContent(), "Reports");
                    Object obj = FileUtils.readSerializedObject(wrapper.getContent());
                    if (obj != null) {
                        FileUtils.writeObjectToReadableFile(this, obj, "report_readable.txt");
                    }*/
                    ByteArrayInputStream byteIn = new ByteArrayInputStream( result );
                    ObjectInputStream in = new ObjectInputStream(byteIn);
                    InspectionReport report = ( InspectionReport ) in.readObject();
                    report.setWrapperId( wrapper.getId() );
                    report.setFilePath( wrapper.getContent() );
                    reports.add( report );
                } catch (Exception | OutOfMemoryError e){
                    e.printStackTrace();
                }
            }
        }
        return reports;
    }

    private void logErrorToFile(Throwable throwable) {
        try {
            File logFile = new File(getExternalFilesDir(null), "upload_error_log.txt");
            FileWriter writer = new FileWriter(logFile, true); // append mode
            writer.write("Error: " + throwable.toString() + "\n");
            if (throwable.getMessage() != null) {
                writer.write("Message: " + throwable.getMessage() + "\n");
            }
            StringWriter sw = new StringWriter();
            throwable.printStackTrace(new PrintWriter(sw));
            writer.write(sw.toString());
            writer.write("\n------------------------\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}