from median.constant import EcoType, EtatAdresse, EquipmentType
from median.models import Adresse, Service

from ressources.equipments.store_utils import getColumns_version, add_poste_espace, init_equipment
from ressources.equipments.store_utils import remove_equipment


def generate_riedl(data):
    type = data['type']
    if type == EquipmentType.RIEDL.value:

        nbSortie = int(data['SORTIE'])

        # Magasin
        equipment = init_equipment(data)
        equipment.eco_type = EcoType.Riedl.value
        equipment.nb_dim = 3
        equipment.lib_2 = 'ENTREE'
        equipment.dim_2 = int(data['ENTREE']) + int(data.get('ENTREE_AUTO', 0))
        equipment.lib_3 = 'SORTIE'
        equipment.dim_3 = nbSortie
        equipment.lib_4 = 'URGENCE'
        equipment.dim_4 = int(data['URGENCE'])
        equipment.save()

        columns_version = getColumns_version(data['version'])
        try:
            # Adress
            for column in columns_version:
                adress = Adresse()
                adress.adresse = equipment.mag
                adress.magasin = equipment.mag
                adress.etat = EtatAdresse.Multiple.value
                adress.format = column.catalogcolumns.container_type
                adress.save()

            add_poste_espace(equipment)

            # Ward
            if nbSortie > 0:

                for exit in range(nbSortie):
                    ward = Service()
                    ward.code = f'{equipment.mag}.EX{exit + 1}'
                    ward.libelle = f'Exit {exit + 1} / Sortie {exit + 1}'
                    ward.type_dest = EquipmentType.RIEDL.value
                    ward.secteur = equipment.type_mag
                    ward.save()

                for exit in range(int(data['URGENCE'])):
                    ward = Service()
                    ward.code = f'{equipment.mag}.UR{exit + 1}'
                    ward.libelle = f'Urgence {exit + 1} / Loading Bay {exit + 1}'
                    ward.type_dest = EquipmentType.RIEDL.value
                    ward.secteur = equipment.type_mag
                    ward.save()

            return equipment
        except Exception:
            remove_equipment(equipment)
