def backlog_view(request):
    projektid = request.matchdict['projektid']
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    if username is None:
        return HTTPFound('/login')
    projekt = database.readProjectByProjectid(userid, projektid)
    if type(projekt) is int:
        print("Error: " + replyCodes[projekt])
        return HTTPFound('/scrumboard/' + projektid)
    sprints = database.readSprintsOfProject(userid, projektid)
    if type(sprints) is int:
        print("Error: " + replyCodes[sprints])
        return HTTPFound('/scrumboard/' + projektid)
    #all tickets of project
    tickets = database.readTicketsOfProject(userid, projektid)
    if type(tickets) is int:
        print("Error: " + replyCodes[tickets])
        return HTTPFound('/scrumboard/' + projektid)
    for t in tickets:
        t.prioritaet = priority[t.prioritaet]
        t.typ = typ[t.typ]
        if t.sprintid:
            sprintNr = None
            for s in sprints:
                if s.id == t.sprintid:
                    sprintNr = s.number
                    break
            if sprintNr:
                t.name =  "[In Sprint " + str(sprintNr) + "] " + t.name
    if request.method == 'POST':
        data = request.POST

    return{'tickets' : tickets, 'projekt' : projekt, 'sprints' : sprints}
def backlogsprint_view(request):
    projektid = request.matchdict['projektid']
    sprintnumber = request.matchdict['sprintnumber']
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    if username is None:
        return HTTPFound('/login')
    projekt = database.readProjectByProjectid(userid, projektid)
    if type(projekt) is int:
        print("Error: " + replyCodes[projekt])
        return HTTPFound('/scrumboard/' + projektid)
    sprints = database.readSprintsOfProject(userid, projektid)
    if type(sprints) is int:
        print("Error: " + replyCodes[sprints])
        return HTTPFound('/scrumboard/' + projektid)
    #all tickets of project
    tickets = database.readTicketsOfProject(userid, projektid)
    if type(tickets) is int:
        print("Error: " + replyCodes[tickets])
        return HTTPFound('/scrumboard/' + projektid)
    for t in tickets:
        t.prioritaet = priority[t.prioritaet]
        t.typ = typ[t.typ]
        if t.sprintid:
            sprintNr = None
            for s in sprints:
                if s.id == t.sprintid:
                    sprintNr = s.number
                    break
            if sprintNr:
                t.name =  "[In Sprint " + str(sprintNr) + "] " + t.name
    #tickets of sprint
    sprinttickets = database.readTicketsOfSprint(userid, projektid, sprintnumber)
    if type(sprinttickets) is int:
        print("Error: " + replyCodes[sprinttickets])
        return HTTPFound('/scrumboard/' + projektid)
    for t in sprinttickets:
        t.prioritaet = priority[t.prioritaet]
        t.typ = typ[t.typ]
    if request.method == 'POST':
        data = request.POST
        taskid = data.get('task')
        snr = data.get('sprintnr')
        pid = data.get('pid')
        changed = database.changeTicketSprint(userid, int(taskid), int(snr))
        if changed > 0:
	    print("Error : " + replyCodes[changed])
	    return HTTPFound("/backlog/" + projektid + "/" + sprintnumber)
        
    return{'tickets' : tickets, 'projekt' : projekt, 'sprints' : sprints, 'sprinttickets' : sprinttickets, 'sprintnumber' : int(sprintnumber)}
def scrumboard_view(request):
    projektid = request.matchdict['projektid']
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    session['activeprojectid'] = projektid
    if username is None:
        return HTTPFound('/login')
    #do stuff
    project = database.readProjectByProjectid(userid, projektid)
    if type(project) is int:
        print("Error:" + replyCodes[project])
        return HTTPFound('/dashboard')
        
    dbsprints = database.readSprintsOfProject(userid, projektid)
    if type(dbsprints) is int:
        print("Error: " + replyCodes[dbsprints])
        return HTTPFound('/dashboard')
    sprints = []
    for sprint in dbsprints:
        if not sprint.number == 0:
            sprints.append(sprint)
    
    return{ 'sprints' : sprints, 'project' : projektid, 'projektname' : project.name, 'projektstart' : project.start, 'projektende' : project.end}
def sprint_view(request):
    projektid = request.matchdict['projektid']
    sprintnumber = request.matchdict['sprintnumber']
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    session['activeprojectid'] = projektid

    if username is None:
        return HTTPFound('/login')
    #do stuff
    project = database.readProjectByProjectid(userid, projektid)
    if type(project) is int:
        print("Error:" + replyCodes[project])
        return HTTPFound('/dashboard')
        
    dbsprints = database.readSprintsOfProject(userid, projektid)
    if type(dbsprints) is int:
        print("Error: " + replyCodes[dbsprints])
        return HTTPFound('/dashboard')
    sprints = []
    activesprint = None
    for sprint in dbsprints:
        sprints.append(sprint)
        if sprint.number == int(sprintnumber):
            activesprint = sprint
    if activesprint is None:
        return HTTPFound('/scrumboard/' + projektid)
    sstart = activesprint.start
    send = activesprint.end
    #tasks for sprint
    tasks = database.readTicketsOfSprint(userid, projektid, sprintnumber)
    if type(tasks) is int:
        print("Error: " + replyCodes[tasks])
        return HTTPFound('/scrumboard/' + activeprojectid)
    ausstehend = []
    bearbeitung = []
    testphase = []
    fertig = []
    for ticket in tasks:
        ticket.prioritaet = priority[ticket.prioritaet]
        ticket.typ = typ[ticket.typ]
        if ticket.column == 1:
            ausstehend.append(ticket)
        elif ticket.column == 2:
            bearbeitung.append(ticket)
        elif ticket.column == 3:
            testphase.append(ticket)
        elif ticket.column == 4:
            fertig.append(ticket)
        
    if request.method == 'POST':
        data = request.POST
        tid = data.get('task')
        cid = data.get('column')
        changed = database.changeTicketColumn(userid, int(tid), int(cid))
        if changed > 0:
            print("Error : " + replyCodes[changed])
            return HTTPFound("/scrumboard/" + projektid + "/" + sprintnumber)
    
    return{ 'sprints' : sprints, 'project' : projektid, 'projektname' : project.name, 'sprintnumber' : int(sprintnumber), 'sprintstart' : sstart, 'sprintend' : send , 'ticketausstehend' : ausstehend, 'ticketbearbeitung' : bearbeitung, 'tickettest' : testphase, 'ticketfertig' : fertig}
def projectdetails_view(request):
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    projektid = request.matchdict['projektid']
    if username is None:
        return HTTPFound('/login')

    #POST
    if request.method == 'POST':
        data = request.POST
        
        if "roleselect" in data:
            if data.get("roleselect") == staticValues["REMOVE_FROM_PROJECT_STRING"]:
                #remove student from project
                removed = database.writeRemoveStudentFromProject(userid, projektid, int(data.get("studentId")))
                if removed > 0:
                    print("Error: " + replyCodes[removed])
            else:
                #changing student permissions
                newrole = 100
                for b in range(0,len(permissionLevels)-1):
                    if permissionLevels[b] == data.get("roleselect"):
                        newrole = b
                        break
                changed = database.changeStudentPermissionsInProject(userid, projektid, int(data.get("studentId")), newrole)
                if changed > 0:
                    print("Error: " + replyCodes[changed])
      
    #GET
    projekt = database.readProjectByProjectid(userid, projektid)
    if type(projekt) is int:
        print("Error: " + replyCodes[projekt])
        return HTTPFound('/scrumboard/' + projektid)

    sprints = database.readSprintsOfProject(userid, projektid)
    if type(sprints) is int:
        print("Error: " + replyCodes[sprints])
        return HTTPFound('/scrumboard/' + projektid)

    studentenBerechtigungen = database.readAllUserPermissionLevelInProject(userid, projektid)
    if type(studentenBerechtigungen) is int:
        print("Error: " + replyCodes[studentenBerechtigungen])
        return HTTPFound('/scrumboard/' + projektid)
    permission = database.readUserPermissionLevelInProject(userid, userid, projektid)

    students = database.readStudentsInProject(userid, projektid)  
    if type(students) is int:
        print("Error: " + replyCodes[students])
        return HTTPFound('/scrumboard/' + projektid)
    for s in students:
        s.berechtigung = database.readUserPermissionLevelInProject(userid, s.id, projektid)
        #what can we change about this user?
        s.moeglicheNeueBerechtigungen = []
        aktuelleBerechtigung = permissionLevels[s.berechtigung]
        if permission < projectPermissions["CHANGE_STUDENT_PERMISSIONS"]:
            if permission < s.berechtigung:
                if permission == 0 and s.id != userid:
                    s.moeglicheNeueBerechtigungen.append(permissionLevels[0])
                for p in range(permission+1, len(permissionLevels)-1):
                    s.moeglicheNeueBerechtigungen.append(permissionLevels[p])
                if permission < projectPermissions["REMOVE_STUDENT"]:
                    s.moeglicheNeueBerechtigungen.append(staticValues["REMOVE_FROM_PROJECT_STRING"])
        if len(s.moeglicheNeueBerechtigungen) < 1:
            s.moeglicheNeueBerechtigungen.append(aktuelleBerechtigung)
        if s.id == userid and permission > 0:
            s.moeglicheNeueBerechtigungen.append(staticValues["REMOVE_FROM_PROJECT_STRING"])
        #human readable
        s.berechtigung = permissionLevels[s.berechtigung]

    userrechte = {
        "useradd" : permission < projectPermissions["ADD_STUDENT"] ,
        "projektbearbeiten" : permission < projectPermissions["MAKE_INFO_CHANGES"] ,
        "projektloeschen" : permission < projectPermissions["DELETE_PROJECT"] ,
        "sprintbearbeiten" : permission < projectPermissions["CHANGE_SPRINT"] ,
        "sprintloeschen" : permission < projectPermissions["DELETE_SPRINT"] ,
    }
    
    return{'projekt' : projekt, 'sprints' : sprints, 'students': students, 'userrechte' : userrechte}