package cz.muni.fi.pa165.core.user.roles;

import cz.muni.fi.pa165.core.company.CompanyService;
import cz.muni.fi.pa165.core.helpers.exceptions.EntityDeletionException;
import cz.muni.fi.pa165.core.house.HouseService;
import cz.muni.fi.pa165.core.user.UserService;
import cz.muni.fi.pa165.model.dto.role.CompanyRoleDto;
import cz.muni.fi.pa165.model.dto.role.HouseRoleDto;
import cz.muni.fi.pa165.model.dto.role.RoleDto;
import cz.muni.fi.pa165.model.dto.role.enums.RoleTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RoleFacade {

    private final RoleService roleService;
    private final HouseService houseService;
    private final UserService userService;
    private final CompanyService companyService;
    private final RoleMapper mapper;

    @Autowired
    public RoleFacade(RoleService service, HouseService houseService, UserService userService, CompanyService companyService, RoleMapper mapper) {
        this.roleService = service;
        this.houseService = houseService;
        this.userService = userService;
        this.companyService = companyService;
        this.mapper = mapper;
    }

    public HouseRoleDto createHouseRole(HouseRoleDto entity){
        HouseRole houseRole = mapper.fromHouseDto(entity);
        houseRole.setHouse(houseService.findById(entity.getHouseId()));
        houseRole.setUser(userService.findById(entity.getUserId()));
        // TODO: how to mapp parent properties?
        houseRole.setHouseRole(entity.getHouseRole());
        houseRole.setRoleType(RoleTypeEnum.HouseRole);

        return mapper.toHouseDto((HouseRole) roleService.create(houseRole));
    }

    public CompanyRoleDto createCompanyRole(CompanyRoleDto entity){
        CompanyRole companyRole = mapper.fromCompanyDto(entity);
        companyRole.setCompany(companyService.findById(entity.getCompanyId()));
        companyRole.setUser(userService.findById(entity.getUserId()));
        // TODO: how to mapp parent properties?
        companyRole.setCompanyRoleEnum(entity.getCompanyRole());
        companyRole.setRoleType(RoleTypeEnum.CompanyRole);

        return mapper.toCompanyDto((CompanyRole) roleService.create(companyRole));
    }

    public RoleDto createGeneralRole(RoleDto entity){
        Role role = mapper.fromGeneralDto(entity);
        role.setUser(userService.findById(entity.getUserId()));
        // TODO: how to mapp parent properties?
        role.setRoleType(entity.getRoleType());

        return mapper.toGeneralDto((Role) roleService.create(role));
    }

    public RoleDto deleteCompanyRole(String roleId) throws Exception {
        return mapper.toGeneralDto((Role) roleService.deleteCompanyRole(roleId));
    }

    public List<RoleDto> findAllByUser(String userId){
        return mapper.toGeneralListDto(roleService.findAllByUser(userId));
    }
}
