package com.bcxin.tenant.open.domains.services.impls;

import com.bcxin.tenant.open.domains.entities.RdSecurityStationPersonEntity;
import com.bcxin.tenant.open.domains.repositories.RdSecurityStationPersonRepository;
import com.bcxin.tenant.open.domains.services.SecurityStationPersonService;
import com.bcxin.tenant.open.domains.services.commands.CreateSecurityStationPersonCommand;
import com.bcxin.tenant.open.infrastructures.UnitWork;
import com.bcxin.tenant.open.infrastructures.components.JsonProvider;
import org.springframework.stereotype.Service;

@Service
public class SecurityStationPersonServiceImpl implements SecurityStationPersonService {

    private final UnitWork unitWork;
    private final JsonProvider jsonProvider;
    private final RdSecurityStationPersonRepository securityStationPersonRepository;

    public SecurityStationPersonServiceImpl(UnitWork unitWork,
                                            JsonProvider jsonProvider,
                                            RdSecurityStationPersonRepository securityStationPersonRepository) {
        this.unitWork = unitWork;
        this.jsonProvider = jsonProvider;
        this.securityStationPersonRepository = securityStationPersonRepository;
    }

    @Override
    public void dispatch(CreateSecurityStationPersonCommand command) {
        String tranId = this.unitWork.beginTransaction();
        try
        {
            RdSecurityStationPersonEntity stationPersonEntity = this.jsonProvider.toObject(RdSecurityStationPersonEntity.class,command.getContent());
            if(this.securityStationPersonRepository.getByNoPkId(stationPersonEntity.getId())==null)
            {
                this.securityStationPersonRepository.insert(stationPersonEntity);
            }else {
                this.securityStationPersonRepository.update(stationPersonEntity);
            }

            this.unitWork.commit(tranId);
        }catch (Exception ex)
        {
            this.unitWork.rollback(tranId);
            throw ex;
        }
    }
}
