import io
import os
import csv

from django import forms
from django.core.exceptions import ValidationError

from .models import StudentTracker

STUDENT_TRACKING_HEADER = ['Last Name', 'First Name', 'Email Address', 'Enroll Date', 'Expiration Date',
                           'Grade Recorded', 'Recorded By', 'Date Final Grade Entered', 'Notes', 'edx email or username',
                           '', '', '', '', '', '', '',
                           ]

GRADE_REPORT_HEADER = ['Student ID', 'Email', 'Username', 'Grade', 'Assignments 1: Lesson 2 Assignments',
                       'Assignments 2: Lesson 3 Assignments', 'Assignments 3: Lesson 4 Assignments',
                       'Assignments 4: Lesson 5 Assignments', 'Assignments 5: Lesson 6 Assignment',
                       'Assignments 6: Lesson 7 Assignment', 'Assignments 7: Lesson 8 Assignment',
                       'Assignments 8: Lesson 9 Assignment', 'Assignments 9: Lesson 10 Assignment',
                       'Assignments (Avg)', 'Enrollment Track', 'Verification Status', 'Certificate Eligible',
                       'Certificate Delivered', 'Certificate Type']


def validate_csv_file(file):
    filename, ext = os.path.splitext(file.name)
    if str(ext) != '.csv':
        raise ValidationError("Must be a csv file")
    decoded_file = file.read().decode('utf-8')
    io_string = io.StringIO(decoded_file)
    file_reader = csv.reader(io_string)
    return file_reader


class StudentTrackerForm(forms.ModelForm):
    class Meta:
        model = StudentTracker
        fields = [
            'student_tracking_csv',
            'grade_report_csv',
        ]
        help_texts = {
            'student_tracking_csv': 'Upload a CSV version of the Python 210 SP Student Tracking file from the course'
                                    'OneDrive account.',
            'grade_report_csv': 'Upload a CSV of the student grade report generated by the EdX learning platform.'
        }

    def clean_student_tracking_csv(self):
        student_tracking_file = self.cleaned_data['student_tracking_csv']
        student_tracking_reader = validate_csv_file(student_tracking_file)
        header = next(student_tracking_reader)
        if header != STUDENT_TRACKING_HEADER:
            raise ValidationError("Invalid File. Please upload the Tracking-Table1.csv file from the Student "
                                  "Tracking spreadsheet.")
        return student_tracking_file
    
    def clean_grade_report_csv(self):
        grade_report_file = self.cleaned_data['grade_report_csv']
        grade_report_reader = validate_csv_file(grade_report_file)
        header = next(grade_report_reader)
        if header != GRADE_REPORT_HEADER:
            raise ValidationError("Invalid File. Please upload the grade report CSV file generated by the EdX"
                                  "learning platform.")
        return grade_report_file

