<?php
namespace Modules\Catalogue\Service;

use Entity\Model\FmtMapp;
use Entity\Model\FValDef;
use Entity\Model\StruCata;
use Helpers\Parametres\Constante;

class UpdateValueParamMappageService
{
    private string $idFormat;
    public function __construct(private FmtMapp $fmtMapp, private FValDef $fValDef, private StruCata $struCata)
    {
    }

    public function setFormat(string $idFormat = ''):void
    {
        $this->idFormat = $idFormat;
    }

    public function updateValue(string $fullField, string  $value):void
    {
        list($field, $idLigne) = explode(Constante::spliter, $fullField);

        if (in_array($field, ['ACTIVE', 'TYPEMAPPING', 'POSITION','ELEM_XML','DIVISEUR', 'OBLIGATOI', 'TRANSCOD',  'REGLES', 'VALDEFAUT'])) {
            switch ($field) {
                case 'ACTIVE':
                    $ligneExist = $this->fmtMapp->find(['IDFORMAT' => $this->idFormat, 'LIGNE' => $idLigne]);
                    if (!$ligneExist) {
                        $this->initLigne($idLigne);
                    }

                    $field = 'numerique_ACTIVE';
                    $value = $value == 1? '0x54':'0x46';
                    break;
                case 'OBLIGATOI':
                    $field = 'numerique_OBLIGATOI';
                    $value = $value == 1? '0x54':'0x46';
                    break;
                case 'VALDEFAUT':
                    if (!$value) {
                        $this->fValDef->delete([
                            'IDFORMAT'  => $this->idFormat,
                            'Ligne'     => $idLigne,
                        ]);
                    }
                    break;
            }

            $this->fmtMapp->update([
                $field => $value
            ], [
                'IDFORMAT' => $this->idFormat,
                'LIGNE' => $idLigne
            ]);
        } elseif ($field == 'Valeur_par_defaut') {
            $this->fValDef->merge([
                'IDFORMAT'          => $this->idFormat,
                'Ligne'             => $idLigne,
                'Valeur_par_defaut' => $value,
                'LIGNE'             => 0,
                'VALEUR_PAR_DEFAUT' => ''
            ]);
        }
    }

    private function initLigne(string $idLigne):void
    {

        $infoLigne = $this->struCata->find($idLigne, ['RATTRIBUT']);

        $this->fmtMapp->insert([
            'IDFORMAT'      => $this->idFormat,
            'LIGNE'         => $idLigne,
            'ACTIVE'        => true,
            'POSITION'      => 0,
            'LONGUEUR'      => 0,
            'ELEM_XML'      => '',
            'TYPEMAPPING'   => $infoLigne['RATTRIBUT'] == 'Tab'? 'M':'S',
            'TYPECONTSTR'   => 'N',
        ]);
    }
}
