# -*- mode: python -*-
# -*- coding: utf-8 -*-

"""Fix bug #70

Utiliser comme: 
     scotests/scointeractive.sh DEPT config/fix_bug70_db.py

"""
context = context.Notes  # pylint: disable=undefined-variable
REQUEST = REQUEST  # pylint: disable=undefined-variable
import scotests.sco_fake_gen as sco_fake_gen  # pylint: disable=import-error
import os
import sys
import sco_utils
import notesdb
import sco_formsemestre
import sco_formsemestre_edit
import sco_moduleimpl

G = sco_fake_gen.ScoFake(context.Notes)


def fix_formsemestre_formation_bug70(formsemestre_id):
    """Le bug #70 a pu entrainer des incohérences
    lors du clonage avorté de semestres.
    Cette fonction réassocie le semestre à la formation
    à laquelle appartiennent ses modulesimpls.
    2021-04-23
    """
    sem = sco_formsemestre.get_formsemestre(context, formsemestre_id)
    cursor = notesdb.SimpleQuery(
        context,
        """SELECT m.formation_id 
            FROM notes_modules m, notes_moduleimpl mi 
            WHERE mi.module_id = m.module_id 
            AND mi.formsemestre_id  = %(formsemestre_id)s
            """,
        {"formsemestre_id": formsemestre_id},
    )
    modimpls_formations = set([x[0] for x in cursor])
    if len(modimpls_formations) > 1:
        # this is should not occur
        G.log(
            "Warning: fix_formsemestre_formation_bug70: modules from several formations in sem %s"
            % formsemestre_id
        )
    elif len(modimpls_formations) == 1:
        modimpls_formation_id = modimpls_formations.pop()
        if modimpls_formation_id != sem["formation_id"]:
            # Bug #70: fix
            G.log("fix_formsemestre_formation_bug70: fixing %s" % formsemestre_id)
            sem["formation_id"] = modimpls_formation_id
            context.do_formsemestre_edit(sem, html_quote=False)


formsemestre_ids = [
    x[0]
    for x in notesdb.SimpleQuery(
        context, "SELECT formsemestre_id FROM notes_formsemestre", {}
    )
]
for formsemestre_id in formsemestre_ids:
    fix_formsemestre_formation_bug70(formsemestre_id)