from srblib import Tabular, Email

mainbody = '''Hi {name},

You have been alloted the following duties during exams.

{dutiesdata}

{custom_message}

This is an autogenerated mail from examscheduler.

Regards,

Team ExamScheduler
'''

class Output:
    def __init__(self,filename):
        '''
        belives that file is already compiled
        '''
        self.mat = Tabular()
        self.mat.load_xls(filename,strict=True)

    def json(self):
        debugcols = ['_rank','_total','_res','_credits','s_d_m_d']
        infocols = ['Info','Name of Faculty Member','Total','mail']
        header = []
        for col in self.mat[0]:
            if col in debugcols:
                continue
            header.append(col)

        ret_json = []
        for row in self.mat:
            teacher = dict()
            teacher['duties'] = dict()
            for head in header:
                if head in infocols:
                    teacher[head] = row[head]
                elif row[head] and row[head] != '-':
                    teacher['duties'][head] = row[head]
            ret_json.append(teacher)
        return ret_json



    def mail(self, email, password, custom_message=''):
        subject = "Alloted Duties In examination"
        header = self.mat[0]
        if not 'mail' in header:
            return 0
        sent = 0
        for teacher in self.mat:
            if teacher['mail']:
                data = [[],[]]
                for i in range(0,len(header)-1):
                    if (not teacher[i]) or teacher[i] == '-':
                        continue
                    data[0].append(header[i])
                    data[1].append(teacher[i])
                try:
                    Output.__send_email(email,password,teacher['mail'],Output.__makebody(data,custom_message),subject)
                    sent += 1
                except:
                    pass
        return sent


    @staticmethod
    def __makebody(data,custom_message):
        infocols = ['Info','Name of Faculty Member','Total','mail','_rank','_total','_res','_credits','s_d_m_d']
        duties = ''
        for i in range(len(data[0])):
            print(data[0][i])
            if(data[0][i] in infocols):
                continue
            duties += str(data[0][i]) + ' : ' + str(data[1][i]) + '\n'
        body = mainbody.format(name=data[1][0],dutiesdata=duties,custom_message=custom_message)
        print(body)
        return body

    @staticmethod
    def __send_email(email, password, toaddr, body='', subject=''):
        mail = Email()
        mail.fromaddr = email
        mail.password = password
        mail.toaddr = toaddr
        mail.subject = subject
        mail.body = body
        mail.send()
