from app import db


class Entreprise(db.Model):
    __tablename__ = "are_entreprises"
    id = db.Column(db.Integer, primary_key=True)
    siret = db.Column(db.Text, index=True, unique=True)
    siret_provisoire = db.Column(db.Boolean, default=False)
    nom = db.Column(db.Text)
    adresse = db.Column(db.Text)
    codepostal = db.Column(db.Text)
    ville = db.Column(db.Text)
    pays = db.Column(db.Text)
    association = db.Column(db.Boolean, default=False)
    visible = db.Column(db.Boolean, default=False)
    active = db.Column(db.Boolean, default=True)
    notes_active = db.Column(db.Text)

    sites = db.relationship(
        "EntrepriseSite",
        backref="entreprise",
        lazy="dynamic",
        cascade="all, delete-orphan",
    )

    offres = db.relationship(
        "EntrepriseOffre",
        backref="entreprise",
        lazy="dynamic",
        cascade="all, delete-orphan",
    )

    def to_dict(self):
        return {
            "siret": self.siret,
            "nom_entreprise": self.nom,
            "adresse": self.adresse,
            "code_postal": self.codepostal,
            "ville": self.ville,
            "pays": self.pays,
            "association": self.association,
            "visible": self.visible,
            "active": self.active,
            "notes_active": self.notes_active,
        }


class EntrepriseSite(db.Model):
    __tablename__ = "are_sites"
    id = db.Column(db.Integer, primary_key=True)
    entreprise_id = db.Column(
        db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
    )
    nom = db.Column(db.Text)
    adresse = db.Column(db.Text)
    codepostal = db.Column(db.Text)
    ville = db.Column(db.Text)
    pays = db.Column(db.Text)

    correspondants = db.relationship(
        "EntrepriseCorrespondant",
        backref="site",
        lazy="dynamic",
        cascade="all, delete-orphan",
    )

    def to_dict(self):
        entreprise = Entreprise.query.get_or_404(self.entreprise_id)
        return {
            "siret_entreprise": entreprise.siret,
            "id_site": self.id,
            "nom_site": self.nom,
            "adresse": self.adresse,
            "code_postal": self.codepostal,
            "ville": self.ville,
            "pays": self.pays,
        }


class EntrepriseCorrespondant(db.Model):
    __tablename__ = "are_correspondants"
    id = db.Column(db.Integer, primary_key=True)
    site_id = db.Column(db.Integer, db.ForeignKey("are_sites.id", ondelete="cascade"))
    civilite = db.Column(db.String(1))
    nom = db.Column(db.Text)
    prenom = db.Column(db.Text)
    telephone = db.Column(db.Text)
    mail = db.Column(db.Text)
    poste = db.Column(db.Text)
    service = db.Column(db.Text)
    origine = db.Column(db.Text)
    notes = db.Column(db.Text)

    def to_dict(self):
        site = EntrepriseSite.query.get_or_404(self.site_id)
        return {
            "id": self.id,
            "civilite": self.civilite,
            "nom": self.nom,
            "prenom": self.prenom,
            "telephone": self.telephone,
            "mail": self.mail,
            "poste": self.poste,
            "service": self.service,
            "origine": self.origine,
            "notes": self.notes,
            "nom_site": site.nom,
        }


class EntrepriseContact(db.Model):
    __tablename__ = "are_contacts"
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime(timezone=True))
    user = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))
    entreprise = db.Column(
        db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
    )
    notes = db.Column(db.Text)


class EntrepriseOffre(db.Model):
    __tablename__ = "are_offres"
    id = db.Column(db.Integer, primary_key=True)
    entreprise_id = db.Column(
        db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
    )
    date_ajout = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
    intitule = db.Column(db.Text)
    description = db.Column(db.Text)
    type_offre = db.Column(db.Text)
    missions = db.Column(db.Text)
    duree = db.Column(db.Text)
    expiration_date = db.Column(db.Date)
    expired = db.Column(db.Boolean, default=False)
    correspondant_id = db.Column(
        db.Integer, db.ForeignKey("are_correspondants.id", ondelete="cascade")
    )

    def to_dict(self):
        return {
            "intitule": self.intitule,
            "description": self.description,
            "type_offre": self.type_offre,
            "missions": self.missions,
            "duree": self.duree,
        }


class EntrepriseHistorique(db.Model):
    __tablename__ = "are_historique"
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime(timezone=True), server_default=db.func.now())
    authenticated_user = db.Column(db.Text)
    entreprise_id = db.Column(db.Integer)
    object = db.Column(db.Text)
    object_id = db.Column(db.Integer)
    text = db.Column(db.Text)


class EntrepriseStageApprentissage(db.Model):
    __tablename__ = "are_stages_apprentissages"
    id = db.Column(db.Integer, primary_key=True)
    entreprise_id = db.Column(
        db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
    )
    etudid = db.Column(db.Integer)
    type_offre = db.Column(db.Text)
    date_debut = db.Column(db.Date)
    date_fin = db.Column(db.Date)
    formation_text = db.Column(db.Text)
    formation_scodoc = db.Column(db.Integer)
    notes = db.Column(db.Text)


class EntrepriseTaxeApprentissage(db.Model):
    __tablename__ = "are_taxe_apprentissage"
    id = db.Column(db.Integer, primary_key=True)
    entreprise_id = db.Column(
        db.Integer, db.ForeignKey("are_entreprises.id", ondelete="cascade")
    )
    annee = db.Column(db.Integer)
    montant = db.Column(db.Integer)
    notes = db.Column(db.Text)


class EntrepriseEnvoiOffre(db.Model):
    __tablename__ = "are_envoi_offre"
    id = db.Column(db.Integer, primary_key=True)
    sender_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))
    receiver_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))
    offre_id = db.Column(db.Integer, db.ForeignKey("are_offres.id", ondelete="cascade"))
    date_envoi = db.Column(db.DateTime(timezone=True), server_default=db.func.now())


class EntrepriseEnvoiOffreEtudiant(db.Model):
    __tablename__ = "are_envoi_offre_etudiant"
    id = db.Column(db.Integer, primary_key=True)
    sender_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="cascade"))
    receiver_id = db.Column(
        db.Integer, db.ForeignKey("identite.id", ondelete="cascade")
    )
    offre_id = db.Column(db.Integer, db.ForeignKey("are_offres.id", ondelete="cascade"))
    date_envoi = db.Column(db.DateTime(timezone=True), server_default=db.func.now())


class EntrepriseOffreDepartement(db.Model):
    __tablename__ = "are_offre_departement"
    id = db.Column(db.Integer, primary_key=True)
    offre_id = db.Column(db.Integer, db.ForeignKey("are_offres.id", ondelete="cascade"))
    dept_id = db.Column(db.Integer, db.ForeignKey("departement.id", ondelete="cascade"))


class EntreprisePreferences(db.Model):
    __tablename__ = "are_preferences"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text)
    value = db.Column(db.Text)

    @classmethod
    def get_email_notifications(cls):
        mail = EntreprisePreferences.query.filter_by(
            name="mail_notifications_entreprise"
        ).first()
        if mail is None:
            return ""
        else:
            return mail.value

    @classmethod
    def set_email_notifications(cls, mail: str):
        if mail != cls.get_email_notifications():
            m = EntreprisePreferences.query.filter_by(
                name="mail_notifications_entreprise"
            ).first()
            if m is None:
                prefs = EntreprisePreferences(
                    name="mail_notifications_entreprise",
                    value=mail,
                )
                db.session.add(prefs)
            else:
                m.value = mail
            db.session.commit()

    @classmethod
    def get_check_siret(cls):
        check_siret = EntreprisePreferences.query.filter_by(name="check_siret").first()
        if check_siret is None:
            return 1
        else:
            return int(check_siret.value)

    @classmethod
    def set_check_siret(cls, check_siret: int):
        cs = EntreprisePreferences.query.filter_by(name="check_siret").first()
        if cs is None:
            prefs = EntreprisePreferences(name="check_siret", value=check_siret)
            db.session.add(prefs)
        else:
            cs.value = check_siret
        db.session.commit()


def entreprises_reset_database():
    db.session.query(EntrepriseContact).delete()
    db.session.query(EntrepriseStageApprentissage).delete()
    db.session.query(EntrepriseTaxeApprentissage).delete()
    db.session.query(EntrepriseCorrespondant).delete()
    db.session.query(EntrepriseSite).delete()
    db.session.query(EntrepriseEnvoiOffre).delete()
    db.session.query(EntrepriseEnvoiOffreEtudiant).delete()
    db.session.query(EntrepriseOffreDepartement).delete()
    db.session.query(EntrepriseOffre).delete()
    db.session.query(Entreprise).delete()
    db.session.query(EntrepriseHistorique).delete()
    db.session.query(EntreprisePreferences).delete()
    db.session.commit()
