package cz.muni.fi.pa165.core.house;

import cz.muni.fi.pa165.core.common.DomainFacade;
import cz.muni.fi.pa165.core.helpers.exceptions.EntityDeletionException;
import cz.muni.fi.pa165.core.smartmeter.SmartMeterFacade;
import cz.muni.fi.pa165.model.dto.house.HouseCreateDto;
import cz.muni.fi.pa165.model.dto.house.HouseDto;
import cz.muni.fi.pa165.model.dto.house.HouseUpdateDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class HouseFacade extends DomainFacade<House, HouseDto, HouseCreateDto, HouseUpdateDto> {
	private final HouseService houseService; // For the "HouseService" specific methods

	private final SmartMeterFacade smartMeterFacade;
	@Autowired
	public HouseFacade(HouseService houseService,
					   HouseMapper houseMapper, SmartMeterFacade smartMeterFacade) {
		super(houseService, houseMapper);
		this.houseService = houseService;
		this.smartMeterFacade = smartMeterFacade;
	}

	@Override
	public HouseDto deleteById(String id) throws EntityDeletionException {
		House house = this.houseService.findById(id);
		if (house.getOwnerList().size() > 0 || house.getSmartMeterList().size() > 0)   {
			throw new EntityDeletionException("House", new String[] {"user role", "smart meter"});
		}

		return mapper.toDto(this.houseService.deleteById(id));
	}

	public void deleteHouseWithAllItsEntities(House house) throws EntityDeletionException {
		house.getSmartMeterList().forEach(sm -> {
			try {
				smartMeterFacade.deleteSmartMetersWithItsEntities(sm);
			} catch (EntityDeletionException e) {
				throw new RuntimeException(e);
			}
		});

		this.houseService.deleteById(house.getId());
	}
}