package com.example.quiz;

import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.anggastudio.printama.Printama;
import com.example.quiz.data.model.dtos.paris.SoldeResponse;
import com.example.quiz.databinding.FragmentSoldByCourseBinding;
import com.example.quiz.utils.BitMapUtils;
import com.example.quiz.utils.LoaderDialog;
import com.example.quiz.utils.MessageDialog;
import com.example.quiz.utils.MobiIotPrinterManager;
import com.example.quiz.utils.Result;
import com.example.quiz.utils.SharedPrefsHelper;
import com.example.quiz.utils.SunmiPrinterManager;
import com.example.quiz.viewModel.LogsViewModel;
import com.example.quiz.viewModel.PariViewModel;
import com.google.zxing.WriterException;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SoldByCourse#newInstance} factory method to
 * create an instance of this fragment.
 */

@AndroidEntryPoint
public class SoldByCourse extends Fragment {

    FragmentSoldByCourseBinding binding;
    String mobileName;
    SunmiPrinterManager sunmiPrinterManager;
    MutableLiveData<Boolean> isPrinterReady = new MutableLiveData<>(false);

    LoaderDialog loader;

    LogsViewModel logsViewModel;

    PariViewModel pariViewModel;

    SharedPrefsHelper prefsHelper;


    public static SoldByCourse newInstance() {
        SoldByCourse fragment = new SoldByCourse();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefsHelper = SharedPrefsHelper.getInstance(getContext());
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentSoldByCourseBinding.inflate(inflater, container, false);
        logsViewModel = new ViewModelProvider(this).get(LogsViewModel.class);
        sunmiPrinterManager = SunmiPrinterManager.getInstance(requireContext());
        mobileName = Build.MANUFACTURER;
        if(mobileName.toLowerCase().contains("sunmi")) {
            sunmiPrinterManager.connectPrinter(status -> {
                isPrinterReady.setValue(status);
                sunmiPrinterManager.disableSystemMessages();
            });
        }else{
            MobiIotPrinterManager.getInstance().init(requireContext());
        }
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loader = new LoaderDialog(getContext());
        pariViewModel = new ViewModelProvider(this).get(PariViewModel.class);

        binding.btnCheckBalance.setOnClickListener(v -> {
            if(binding.etRaceNumber.getText().toString().isEmpty()){
                binding.etRaceNumber.setError("Veuillez entrer un numéro de course");
                return;
            }
            pariViewModel.getSoldeByCourse(prefsHelper.get("id"), binding.etRaceNumber.getText().toString()).observe(getViewLifecycleOwner(), new Observer<Result<SoldeResponse>>() {
                @Override
                public void onChanged(Result<SoldeResponse> doubleResult) {
                    switch (doubleResult.status){
                        case LOADING:{
                            loader.show("Chargement du solde");
                            break;
                        }
                        case ERROR:{
                            loader.dismiss();
                            MessageDialog.showError(getContext(), doubleResult.message);
                            break;
                        }
                        case SUCCESS:{
                            loader.dismiss();
                            try {
                                _showPariDialog(doubleResult.data, binding.etRaceNumber.getText().toString());
                            } catch (WriterException e) {
                                throw new RuntimeException(e);
                            }
                            logsViewModel.insertLog(prefsHelper.get("id"), "SOLDE COURSE", "Solde de la course "+binding.etRaceNumber.getText(), System.currentTimeMillis());
                            break;
                        }
                    }
                }
            });
        });
    }

    void _showPariDialog(SoldeResponse soldeResponse, String numero) throws WriterException {
        try {
            int solde = soldeResponse.getMontantParis() - soldeResponse.getMontantAnnulations() - soldeResponse.getMontantPaiements();
            new  AlertDialog.Builder(getContext())
                    .setTitle("Solde")
                    .setMessage("Solde la course "+solde)
                    .setNeutralButton("Ok", (dialog, which) -> {
                        binding.etRaceNumber.setText("");
                        dialog.dismiss();
                    })
                    .setPositiveButton("Imprimer", (dialog, which)->{
                        if(mobileName.toLowerCase().contains("sunmi")){
                            if(isPrinterReady.getValue() == null || !isPrinterReady.getValue()){
                                sunmiPrinterManager.connectPrinter(status ->{
                                    isPrinterReady.setValue(status);
                                });
                            }
                            if(sunmiPrinterManager.printerStatus() != 1){
                                MessageDialog.showError(getContext(), "Erreur lors de l'impréssion, Veuillez rééssayer S.V.P!");
                                return;
                            }
                        }else{
                            try {
                                int status = MobiIotPrinterManager.getInstance().getPrinterStatus();
                                if(status != 1){
                                    MessageDialog.showError(getContext(), "Erreur lors de l'impréssion, Veuillez rééssayer S.V.P!");
                                    return;
                                }
                            } catch (RemoteException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.drawable.pmu_logo);
                        String title = "SOLDE DE LA COURSE "+numero;
                        StringBuilder text = new StringBuilder();
                        text.append("VENTES HIPPIQUES: ").append(BitMapUtils.formatMontant(soldeResponse.getMontantParis())).append(" XOF").append("\n");
                        text.append("NBR. PAIEMENTS: ").append(BitMapUtils.formatMontant(soldeResponse.getNombrePaiements())).append("\n");
                        text.append("PAIEMENTS: ").append(BitMapUtils.formatMontant(soldeResponse.getMontantPaiements())).append(" XOF").append("\n");
                        text.append("NBR. ANNULATIONS: ").append(BitMapUtils.formatMontant(soldeResponse.getNombreAnnulations())).append("\n");
                        text.append("ANNULATIONS: ").append(BitMapUtils.formatMontant(soldeResponse.getMontantAnnulations())).append(" XOF").append("\n");
                        text.append(sunmiPrinterManager.separationText()).append("\n");
                        text.append("SOLDE: ").append(BitMapUtils.formatMontant(solde)).append(" XOF").append("\n");
                        text.append(sunmiPrinterManager.separationText()).append("\n");
                        text.append("AGENT     :  ").append(prefsHelper.get("code")).append("\n");
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
                        String now = formatter.format(LocalDateTime.now());
                        text.append("DATE      :  ").append(now).append("\n");
                        if(mobileName.toLowerCase().contains("sunmi")){
                            sunmiPrinterManager.printSold(BitMapUtils.resizeToPrinterWidth(logo, 384), title, text, status -> {
                                if(!status){
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            MessageDialog.showError(getContext(), "Une erreur s'est produite lors de l'impréssion."+"\n"+"Veuillez rééssayer S.V.P!");
                                        }
                                    });
                                }
                            });
                        }else{
                            try {
                                MobiIotPrinterManager.getInstance().printSold(BitMapUtils.bitmapToBmp(BitMapUtils.resizeToPrinterWidth(logo, 384)), title, text, new MobiIotPrinterManager.MobiIotPrinterStatus() {
                                    @Override
                                    public void printStatusCode(int status) {
                                        if(status != 1){
                                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MessageDialog.showError(getContext(), "Une erreur s'est produite lors de l'impréssion."+"\n"+"Veuillez rééssayer S.V.P!");
                                                }
                                            });
                                        }
                                    }
                                });
                            } catch (RemoteException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    })
                    .show();
        }catch (SecurityException e){
            MessageDialog.showError(getContext(), "Erreur lors de l'affichage du solde");
        }
    }
}