fileobj.close()
    for mail in mails_list:
        in_batch = False
        for batch in values['batches']:
            if (mail in mails_data[batch]):
                in_batch = True
                data[batch].append(mail)
                break
        if (not in_batch):
            #ONLY the amritapurifoss mail is supposed to be printed. If any other mail is being printed then it means that the mail is not there in maildata.json and must be added!!
            app.logger.info("The following mail was not there in the database " + mail)

    if (len(data['2015']) == 0 and len(data['2016']) == 0 and len(data['2017']) == 0):
        return
    file = open("jsondata/"+filename+".txt",'w+')
    json.dump(data,file)
    file.close()

if __name__ == '__main__':
    date = get_today_date()
    #The returned date will be in the format dd-mm-yy
    #We need the format to be dd-mm-yyyy
    date = date[:-2] + "2018"
    print ("Currently at " + date)
    email_to_content = getdata(date)
    if (email_to_content != {}):
        #Send the mails iff the status update thread has been initiated
        emails = [key for key in email_to_content]
        convert_to_json_and_store(emails,date)
        send_mails_to_users(email_to_content,date)
def list_statistics(chatId, message):
    batches = values['batches']
    summary_message = "Statistics of "
    os.chdir('/home/sandeshghanta/mysite/')
    args = list(message.strip().split())

    try:
        if (args[0] == '-a'):
            summary_message = summary_message + "all users "
            args.insert(1, "allmail")
        elif (args[0] == '-i'):
            try:
                is_valid = is_valid_mail(args[1])
                if (not is_valid):
                    message = str(args[1]) + " is not a valid mail"
                    send_message(chatId, message)
                    return
            except IndexError:
                message = "Argument for -i not provided"
                send_message(chatId, message)
                return
            summary_message = summary_message + "of the individual " + args[
                1] + " "
        elif (args[0] == '-b'):
            try:
                if (args[1] not in batches):
                    message = str(
                        args[1]
                    ) + " is not a valid batch. The available batches are " + ', '.join(
                        batches)
                    send_message(chatId, message)
                    return
            except IndexError:
                message = "Argument for -b not provided"
                send_message(chatId, message)
                return
            summary_message = summary_message + "of the batch " + args[1] + " "
        else:
            errormsg = """Please check your arguments """ + args[
                0] + """ is not a valid option. The available options are -i, -g, -a
            -i stands for individual report. You can give an email as input
            -b stands for batch report. You can give a batch name as inputself.
            -a stands for overall report"""
            send_message(chatId, errormsg)
            return
    except IndexError:
        errormsg = "The first argument for /statistics method i.e -i,-a,-b is not provided"
        send_message(chatId, errormsg)
        return
    try:
        if (args[2] == '-h'):
            start_date = "01-07-18"
            args.insert(3, start_date)
            args.insert(4, get_today_date())
            summary_message = summary_message + "from " + start_date + " to " + str(
                get_today_date()) + ". "
        elif (args[2] == '-d'):
            if (len(args) == 3):
                args.insert(3, get_today_date())
                args.insert(4, get_today_date())
            else:
                is_valid, errormsg = is_valid_date(args[3])
                if (not is_valid):
                    user_provided_chart_flag = ' '.join(args[3:])
                    user_provided_chart_flag = user_provided_chart_flag.lower()
                    if not (user_provided_chart_flag == '-line'
                            or user_provided_chart_flag == '-pie'):
                        errormsg = errormsg + ". Also {0} is not a chart flag. The availabe chart flags are -line and -pie".format(
                            user_provided_chart_flag)
                        message = errormsg
                        send_message(chatId, message)
                        return
                    else:  #The user has provided a valid chart flag as the third argument. It means that the command is of the format -d -pie/-line
                        args.insert(3, get_today_date())
                else:
                    args[
                        3] = errormsg  #If the date is valid then the is_valid_date method returns the modified date
                is_valid, errormsg = is_smaller_than_today(args[3])
                if (not is_valid):
                    message = errormsg
                    send_message(chatId, message)
                    return
                else:
                    args[
                        3] = errormsg  #If the date is valid then the is_valid_date method returns the modified date
                args.insert(
                    4, args[3]
                )  #To maintain uniformity all the dates are in the -p format. If there is only one day 'x' then the program will search from x to x
            summary_message = summary_message + "on the day " + str(
                get_today_date()) + ". "
        elif (args[2] == '-p'):
            try:
                for i in range(
                        3,
                        5):  #i takes the values 3,4 args[i] denotes the dates
                    is_valid, errormsg = is_valid_date(args[i])
                    if (not is_valid):
                        message = errormsg
                        send_message(chatId, message)
                        return
                    else:
                        args[
                            i] = errormsg  #if is_valid is true then errormsg is actually the formatted value of the date
                    is_valid, errormsg = is_smaller_than_today(args[i])
                    if (not is_valid):
                        message = errormsg
                        send_message(chatId, message)
                        return
                    else:
                        args[i] = errormsg
                summary_message = summary_message + "from " + str(
                    args[3]) + " to " + str(args[4]) + ". "
            except IndexError:
                message = "-p flag requires two dates to be given. Two dates were not given"
                send_message(chatId, message)
                return
        else:
            errormsg = "The avaiable options for time are -d -p -a. " + args[
                2] + " is not a valid option " + """
            -d stands for a particular day. You can give a date input after this. The format is dd-mm-yy If no input is given after the -d flag today's date is taken by default
            -p stands for a period. You can give a two dates after the -p flag. Both the dates should be in dd-mm-yy format. The first date stands for the start date and the second date stands for end date. If the end date is not given the default value is the current date
            -h stands for history. The statistics returned will be from the start of time to the current date """
            send_message(chatId, errormsg)
            return
    except IndexError:
        errormsg = "The /statistics must require a time flag. The avaiable options are -d, -p, -h"
        send_message(chatId, errormsg)
        return
    #The Code below gets the statistics
    user_provided_chart_flag = ""
    if (len(args) > 5):
        user_provided_chart_flag = ''.join(args[5:])
        user_provided_chart_flag = user_provided_chart_flag.lower()
        if not (user_provided_chart_flag == '-line'
                or user_provided_chart_flag == '-pie'):
            errormsg = user_provided_chart_flag + " is not a valid chart flag. The valid options are -line and -pie"
            send_message(chatId, errormsg)
            return
    start_date = datetime.datetime.strptime(args[3], '%d-%m-%y')
    end_date = datetime.datetime.strptime(args[4], '%d-%m-%y')
    if (start_date > end_date):
        error_msg = "Start Date is greater than End Date. Please recheck your input!!"
        send_message(chatId, error_msg)
        return
    file = open('maildata.json', 'r')
    mail_json_data = json.load(file)
    file.close()
    count_of_students_in_batch = {}
    for batch in batches:
        count_of_students_in_batch[batch] = len(mail_json_data[batch])
    chart_data = []
    recieved_mails = 0
    expected_mails = 0
    while (start_date <= end_date):
        file_name = start_date.strftime('%d-%m-%y')
        try:
            with open('jsondata/' + file_name + '.txt') as fileobj:
                json_file_data = json.load(fileobj)
                if (args[0] == '-b'):
                    recieved_mails = recieved_mails + len(
                        json_file_data[args[1]])
                    expected_mails = expected_mails + count_of_students_in_batch[
                        args[1]]
                    chart_data.append((file_name, len(json_file_data[args[1]]),
                                       count_of_students_in_batch[args[1]]))
                elif (args[0] == '-i'):
                    sent = 0
                    for batch in json_file_data:
                        if (args[1] in json_file_data[batch]):
                            sent = 1
                            break
                    recieved_mails = recieved_mails + sent
                    expected_mails = expected_mails + 1
                    chart_data.append((file_name, sent, 1))
                elif (args[0] == '-a'):
                    sent = 0
                    for batch in json_file_data:
                        sent = sent + len(json_file_data[batch])
                    total_no_of_students_in_batches = 0
                    for batch in count_of_students_in_batch:
                        total_no_of_students_in_batches = total_no_of_students_in_batches + count_of_students_in_batch[
                            batch]
                    recieved_mails = recieved_mails + sent
                    expected_mails = expected_mails + total_no_of_students_in_batches
                    chart_data.append(
                        (file_name, sent, total_no_of_students_in_batches))
        except FileNotFoundError:
            #send_admin_message(file_name+'.txt' + " is not there in the server!!!")
            do_nothing = 1
        start_date = start_date + datetime.timedelta(days=1)
    summary_message = summary_message + str(
        recieved_mails) + " mails recieved," + str(
            expected_mails) + " were expected."

    #Below we are checking what type of chart the user asked for
    if (user_provided_chart_flag == ""):
        if (
                args[2] != '-d'
        ):  #If -d flag is given the default option is pie and it cannot be changed
            pie = False
            if (args[0] == '-i'):
                pie = True
        else:
            pie = True
    else:
        if (user_provided_chart_flag == "-line"):
            pie = False
        else:
            pie = True
    pic_url = draw_chart(chart_data, recieved_mails, expected_mails, pie)

    summary_message = summary_message + " " + pic_url
    send_message(chatId, summary_message)