import logging

from requests.exceptions import HTTPError

from assigner.backends.base import RepoError
from assigner.backends.decorators import requires_config_and_backend
from assigner.backends.exceptions import UserInAssignerGroup
from assigner.roster_util import get_filtered_roster
from assigner import progress

from redkyn.canvas import CanvasAPI
from redkyn.canvas.utils import lookup_canvas_ids
import datetime

help = "Grants students access to their repos"

logger = logging.getLogger(__name__)


def set_unlock_time(conf, hw_name: str) -> None:
    canvas = CanvasAPI(conf["canvas-token"], conf["canvas-host"])
    section_ids, assignment_ids = lookup_canvas_ids(
        conf["canvas-courses"], canvas, hw_name
    )
    for section, s_id in section_ids.items():
        canvas.put_assignment(
            s_id,
            assignment_ids[section],
            {
                "assignment[unlock_at]": datetime.datetime.now().strftime(
                    "%Y-%m-%dT%H:%M:%S%Z"
                )
            },
        )


def open_assignment(repo, student, access):
    try:
        logging.debug("Opening %s...", repo.name)
        repo.add_member(student["id"], access)
    except HTTPError as e:
        if e.response.status_code == 409:
            logging.warning(
                "%s is already a member of %s.", student["username"], repo.name
            )
        else:
            raise


@requires_config_and_backend
def open_all_assignments(conf, backend, args):
    """Adds each student in the roster to their respective homework
    repositories as Developers so they can pull/commit/push their work.
    """
    hw_name = args.name
    namespace = conf.namespace
    semester = conf.semester
    backend_conf = conf.backend

    roster = get_filtered_roster(conf.roster, args.section, args.student)

    # Don't reset the unlock when changing perms for single student
    if not args.student:
        set_unlock_time(conf, hw_name)

    count = 0
    for student in progress.iterate(roster):
        username = student["username"]
        student_section = student["section"]
        full_name = backend.student_repo.build_name(
            semester, student_section, hw_name, username
        )

        try:
            repo = backend.student_repo(backend_conf, namespace, full_name)
            if "id" not in student:
                student["id"] = backend.repo.get_user_id(username, backend_conf)

            open_assignment(repo, student, backend.access.developer)
            count += 1
        except UserInAssignerGroup:
            logging.info(
                "%s already has access via group membership, skipping...", username
            )
        except RepoError:
            logging.warning("Could not add %s to %s.", username, full_name)

    print("Granted access to {} repositories.".format(count))


def setup_parser(parser):
    parser.add_argument("name", help="Name of the assignment to grant access to")
    parser.add_argument("--section", nargs="?", help="Section to grant access to")
    parser.add_argument(
        "--student", metavar="id", help="ID of the student to assign to."
    )
    parser.set_defaults(run=open_all_assignments)

@@ -315,724 +315,91 @@
 ss%0A%0A
-from redkyn.canvas import CanvasAPI%0Afrom redkyn.canvas.utils import lookup_canvas_ids%0Aimport datetime%0A%0Ahelp = %22Grants students access to their repos%22%0A%0Alogger = logging.getLogger(__name__)%0A%0A%0Adef set_unlock_time(conf, hw_name: str) -%3E None:%0A    canvas = CanvasAPI(conf%5B%22canvas-token%22%5D, conf%5B%22canvas-host%22%5D)%0A    section_ids, assignment_ids = lookup_canvas_ids(%0A        conf%5B%22canvas-courses%22%5D, canvas, hw_name%0A    )%0A    for section, s_id in section_ids.items():%0A        canvas.put_assignment(%0A            s_id,%0A            assignment_ids%5Bsection%5D,%0A            %7B%0A                %22assignment%5Bunlock_at%5D%22: datetime.datetime.now().strftime(%0A                    %22%25Y-%25m-%25dT%25H:%25M:%25S%25Z%22%0A                )%0A            %7D,%0A        
+help = %22Grants students access to their repos%22%0A%0Alogger = logging.getLogger(__name__
 )%0A%0A%0A
@@ -645,33 +645,16 @@
 warning(
-%0A                
 %22%25s is a
@@ -704,37 +704,24 @@
 %5D, repo.name
-%0A            
 )%0A        el
@@ -1164,141 +1164,8 @@
 t)%0A%0A
-    # Don't reset the unlock when changing perms for single student%0A    if not args.student:%0A        set_unlock_time(conf, hw_name)%0A%0A
     
@@ -1355,29 +1355,16 @@
 ld_name(
-%0A            
 semester
@@ -1381,16 +1381,68 @@
 section,
+%0A                                                   
  hw_name
@@ -1451,25 +1451,16 @@
 username
-%0A        
 )%0A%0A     
@@ -1814,33 +1814,16 @@
 ng.info(
-%0A                
 %22%25s alre
@@ -1881,29 +1881,16 @@
 username
-%0A            
 )%0A      
@@ -2107,16 +2107,40 @@
 (%22name%22,
+%0A                       
  help=%22N
@@ -2229,16 +2229,40 @@
 rgs=%22?%22,
+%0A                       
  help=%22S
@@ -2313,25 +2313,16 @@
 rgument(
-%0A        
 %22--stude
@@ -2339,16 +2339,40 @@
 ar=%22id%22,
+%0A                       
  help=%22I
@@ -2402,21 +2402,16 @@
 ign to.%22
-%0A    
 )%0A    pa

Revert "feat: when an assignment is opened, set the Canvas unlock date for cheat-checking purposes later"