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 taskdelete_view(request):
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    taskid = request.matchdict['taskid']
    if username is None:
        return HTTPFound('/login')
      
    task = database.readTicketByTicketid(userid, taskid)
    if type(task) is int:
        print("Error: " + replyCodes[task])
        return HTTPFound('/dashboard')
    projekt = database.readProjectByProjectid(userid, task.projektid)
    if type(projekt) is int:
        print("Error: " + replyCodes[projekt])
        return HTTPFound('/dashboard')
      
    if request.method == 'POST':
        data = request.POST
        deleted = database.deleteTicket(userid, taskid)
        if deleted > 0:
	    return HTTPFound('/taskdelete/' + taskid)
	return HTTPFound('/scrumboard/' + str(task.projektid))  

    return{'task' : task, 'projekt': projekt}
def sprintdelete_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')
      
    sprint = database.readSprintOfProject(userid, int(projektid), int(sprintnumber))
    if type(sprint) is int:
        print("Error:" + replyCodes[sprint])
        return HTTPFound('/scrumboard/' + projektid + '/' + sprintnumber)
    projekt = database.readProjectByProjectid(userid, projektid)
    if type(projekt) is int:
        print("Error: " + replyCodes[projekt])
        return HTTPFound('/scrumboard/' + projektid + '/' + sprintnumber)
      
    if request.method == 'POST':
        data = request.POST
        deleted = database.deleteSprint(userid, sprint.id)
        if deleted > 0:
	    print("Error: " + replyCodes[deleted])
	return HTTPFound('/projectdetails/' + projektid)
        
    return{'sprint' : sprint, 'projekt' : projekt}
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 chart_view(request):
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    projektid = request.matchdict['projektid']
    sprintnumber = request.matchdict['sprintnumber']
    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 + "/" + sprintnumber)
      
    sprint = database.readSprintOfProject(userid, projektid, sprintnumber)
    if type(sprint) is int:
        print("Error! " + replyCodes[sprint])
        return HTTPFound("/scrumboard/" + projektid + "/" + sprintnumber)  
      
    tickets = database.readTicketsOfSprint(userid, projektid, sprintnumber)
    if type(tickets) is int:
        print("Error! " + replyCodes[tickets])
        return HTTPFound("/scrumboard/" + projektid + "/" + sprintnumber)
      
    totaleffort = 0
    for ticket in tickets:
        totaleffort = totaleffort + ticket.effort
        
    dateEffortValues = []
    curDate = sprint.start
    curEffortHeight = totaleffort
    while curDate <= sprint.end:
        for t in tickets:
	    if curDate == t.finished:
	        curEffortHeight = curEffortHeight - t.effort
        dateEffortValues.append({
	    'remainingEffort':curEffortHeight,
	    'datum':str(curDate.day) + '.' + str(curDate.month)
        })
        curDate = curDate + timedelta(days=1)
        
    ticketdata = {}
    ticketdata['totaleffort'] = totaleffort
    ticketdata['dateEffortValues'] = dateEffortValues
    ticketdata['daysNum'] = len(ticketdata['dateEffortValues'])
        
    return{'projekt' : projekt, 'sprint' : sprint, 'tickets' : tickets, 'ticketdata' : ticketdata}
def projectmodify_view(request):
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    projektid = request.matchdict['projektid']
    if username is None:
        return HTTPFound('/login')
      
    projekt = database.readProjectByProjectid(userid, projektid)
    if type(projekt) is int:
        print("Error: " + replyCodes[projekt])
        return HTTPFound('/projectdetails/' + projektid)
      
    if request.method == 'POST':
        data = request.POST
        projectM = projektModel()
        projectM.id = projekt.id

        if "projectTitle" in data:
            projectM.name = data.get("projectTitle")
        else:
            projectM.name = projekt.name
            
        if "projectDescription" in data:
            projectM.description = data.get("projectDescription")
        else:
            projectM.description = projekt.description
        
        if "projectStart" in data:
            projectM.start = utils.tryParseDate(data.get("projectStart"))
        else:
            projectM.start = projekt.start
            
        if "projectEnd" in data:
            projectM.end = utils.tryParseDate(data.get("projectEnd"))
        else:
            projectM.end = projekt.end

        if not utils.tryParseDate(projectM.start) or not utils.tryParseDate(projectM.end):
            return HTTPFound('/projectdetails/' + projektid)

        changed = database.changeProjectInfo(userid, projectM)
        if changed > 0:
            print("Error: " + replyCodes[changed])
        
    return{'projekt' : projekt}
def projectdelete_view(request):
    session = request.session
    username = session.get("user")
    userid = session.get("userid")
    projektid = request.matchdict['projektid']
    if username is None:
        return HTTPFound('/login')
      
    projekt = database.readProjectByProjectid(userid, projektid)
    if type(projekt) is int:
        print("Error: " + replyCodes[projekt])
        return HTTPFound('/projectdetails/' + projektid)
    
    if request.method == 'POST':
        data = request.POST
        deleted = database.deleteProject(userid, projektid)
        if deleted > 0:
    	    print("Error: " + replyCodes[deleted])
        return HTTPFound('/projectdelete/' + projektid)
	return HTTPFound('/dashboard')
        
    return{'projekt' : projekt}
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}