package com.utopiaindustries.qualitychecker.ui.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
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.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;

import com.utopiaindustries.qualitychecker.R;
import com.utopiaindustries.qualitychecker.db.ReportRepository;
import com.utopiaindustries.qualitychecker.models.InspectionReport;
import com.utopiaindustries.qualitychecker.models.InspectionReportWrapper;
import com.utopiaindustries.qualitychecker.store.Store;
import com.utopiaindustries.qualitychecker.ui.fragments.FirstStepFragment;
import com.utopiaindustries.qualitychecker.ui.fragments.SecondStepFragment;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.utopiaindustries.qualitychecker.ui.fragments.ThirdStepFragment;
import com.utopiaindustries.qualitychecker.utils.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private NavController navController;
    private Store store;
    private String fromClass;
    private String draftReportId;

    private static final int CAMERA_REQUEST = 10111;
    private static final int GALLERY_REQUEST = 20111;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        store = Store.getInstance();
        store.initializeNewReport( getApplicationContext() );
        setContentView(R.layout.activity_main);
        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 );

        fromClass = getIntent().getStringExtra("fromClass");
        draftReportId = getIntent().getStringExtra("draftID");

        if (fromClass.equalsIgnoreCase("Draft")) {
            System.out.println("Draft Report ID: " + draftReportId);

        }

        navController = Navigation.findNavController( this, R.id.nav_host_fragment);
        // initializing fields
        updateUsername();

    }
    private void updateUsername() {
        if ( store.getReport() != null ) {
            SharedPreferences sharedPreferences = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
            String username = sharedPreferences.getString("username", null);
            store.getReport().setGeneratedBy(username);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        System.out.println( navController.getCurrentDestination().getId() );
        navigate("","",R.id.action_firstStepFragment_to_secondStepFragment );
    }

    private void navigate(String fromFragment,
                          String toFragment,
                          int toId ){
        System.out.println( navController.getCurrentDestination().getId() );
        navController.navigate( toId );
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("requestCode: ",""+requestCode);
        Log.e("resultCode: ",""+resultCode);
        Log.e("data: ",""+data);
        Log.e("-----------------------","---------------------");

        if (requestCode == IntentIntegrator.REQUEST_CODE) {
            Log.e("Zxing barcode scan: ","-----");

            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

            if (result != null) {
                if (result.getContents() == null) {
                    Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                } else {
                    super.onActivityResult(requestCode, resultCode, data);
                    FirstStepFragment firstStepFragment = ( FirstStepFragment) getCurrentVisibleFragment();
                    firstStepFragment.onBarcodeScanResult( result.getContents() );
                }
            }
        }
        else if (requestCode == CAMERA_REQUEST) {
            ThirdStepFragment thirdStepFragment = ( ThirdStepFragment) getCurrentVisibleFragment();
            thirdStepFragment.onImagePickerResult( requestCode, resultCode, data );
        }
        else if (requestCode == GALLERY_REQUEST) {
            ThirdStepFragment thirdStepFragment = ( ThirdStepFragment) getCurrentVisibleFragment();
            thirdStepFragment.onImagePickerResult( requestCode, resultCode, data );
        }
        else if (requestCode != -1 && resultCode == -1 && data == null) {
            Log.e("camera ","------- camera ***");
            SecondStepFragment secondStepFragment = ( SecondStepFragment) getCurrentVisibleFragment();
            secondStepFragment.onImagePickerResult( requestCode, resultCode, data );
        }
        else if (requestCode != -1 && resultCode == -1 && data != null) {
            Log.e("gallery ","------ gallery ***");
            SecondStepFragment secondStepFragment = ( SecondStepFragment) getCurrentVisibleFragment();
            secondStepFragment.onImagePickerResult( requestCode, resultCode, data );
        }
    }

    private Fragment getCurrentVisibleFragment() {
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().getPrimaryNavigationFragment();
        assert navHostFragment != null;
        FragmentManager fragmentManager = navHostFragment.getChildFragmentManager();
        return fragmentManager.getPrimaryNavigationFragment();
    }

    private InspectionReport getSingleReport(InspectionReportWrapper wrapper) {
        InspectionReport report = null;

        if (wrapper != null) {
            try {
                // Get byte array from file content path
                byte[] result = FileUtils.readFile(wrapper.getContent());

                // Convert byte array to an InspectionReport object
                ByteArrayInputStream byteIn = new ByteArrayInputStream(result);
                ObjectInputStream in = new ObjectInputStream(byteIn);
                report = (InspectionReport) in.readObject();

                // Set additional details from the wrapper
                report.setWrapperId(wrapper.getId());
                report.setFilePath(wrapper.getContent());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return report;
    }


}