import datetime
import logging
import os
import traceback
import uuid
import requests
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import pymongo
import yagmail
import img2pdf
from PIL import Image
from flask import Flask, request, redirect, url_for, flash, render_template, send_from_directory
from flask import request, Blueprint, jsonify
from pymongo import MongoClient, DESCENDING
from scripts.common.config import ATTENDANCE_MONGO_HOST, ATTENDANCE_MONGO_PORT, ATTENDANCE_MONGO_DATABASE, \
    ATTENDANCE_MONGO_INVOICES_COLLECTION, ATTENDANCE_MONGO_AUTH, ATTENDANCE_MONGO_USERNAME, ATTENDANCE_MONGO_PASSWORD, \
    ATTENDANCE_MONGO_REGISTER_COLLECTION, ATTENDANCE_MONGO_JOB_COLLECTION, ATTENDANCE_MONGO_MODEL_COLLECTION
from scripts.handlers.test_invoices import test_invoices
from scripts.common.logsetup import logger
from flask_restplus import Resource, Api, reqparse
from scripts.constants.app_constants import APIEndPoints, RequestMethods
from models.model import *
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
import queue
from threading import Thread
from csv import DictWriter, writer
import csv

q = queue.Queue()
retry_queue = queue.Queue()
invoices_blueprint = Blueprint('invoices_services', __name__)
api = Api(invoices_blueprint)
api.add_namespace(invoice_namespace)

if ATTENDANCE_MONGO_AUTH.lower() == 'false:':
    attendance_mongo = MongoClient(ATTENDANCE_MONGO_HOST, int(ATTENDANCE_MONGO_PORT))
else:
    attendance_mongo = MongoClient(host=ATTENDANCE_MONGO_HOST, port=int(ATTENDANCE_MONGO_PORT),
                                   username=ATTENDANCE_MONGO_USERNAME, password=ATTENDANCE_MONGO_PASSWORD)

attendance_database = attendance_mongo[ATTENDANCE_MONGO_DATABASE]
invoice_collection = attendance_database[ATTENDANCE_MONGO_INVOICES_COLLECTION]
register_collection = attendance_database[ATTENDANCE_MONGO_REGISTER_COLLECTION]
job_collection = attendance_database[ATTENDANCE_MONGO_JOB_COLLECTION]
model_collection = attendance_database[ATTENDANCE_MONGO_MODEL_COLLECTION]
ALLOWED_EXTENSIONS = set(['pdf', 'png', 'jpeg', 'jpg'])
UPLOAD_FOLDER = "data"
file_upload = Namespace(name="files")
upload_parser = reqparse.RequestParser(bundle_errors=True)

upload_parser.add_argument(
    name="file",
    type=FileStorage,
    location="files", required=True
    # action="append"  # If this is removed it works with 1 file
)
upload_parser.add_argument(
    name="registerId",
    location='form', type='string', required=True
)
upload_parser.add_argument(
    name="logisticsType",
    location='form', type='string', required=True
)

retry_parser = reqparse.RequestParser(bundle_errors=True)
retry_parser.add_argument(
    name="file",
    type=FileStorage,
    location="files", required=True
    # action="append"  # If this is removed it works with 1 file
)
retry_parser.add_argument(
    name="documentId",
    location='form', type='string', required=True
)
retry_parser.add_argument(
    name="registerId",
    location='form', type='string', required=True
)
retry_parser.add_argument(
    name="logisticsType",
    location='form', type='string', required=True
)


def append_dict_as_row(file_name, dict_of_elem, field_names):
    # Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
        # Create a writer object from csv module
        dict_writer = DictWriter(write_obj, fieldnames=field_names)
        # Add dictionary as wor in the csv
        print(dict_writer)
        dict_writer.writerow(dict_of_elem)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def insert_job(job):
    jobValue = {
        "jobId": job["jobId"],
        "insertedOn": datetime.datetime.now(),
        "updatedOn": datetime.datetime.now(),
        "status": "Queued",
        "documentId": job["documentId"],
        "registerId": job["registerId"],
        "logisticsType": job['logisticsType'],
        "path": job['fileName'],
        "fileName": job['fileName'],
        "actualfile": job["actualfile"]
    }
    logger.info("job inserted")
    job_collection.insert(jobValue)

    return "job inserted"


def update_job(job, status):
    myQuery = {'jobId': job["jobId"]}
    jobValue = {
        "jobId": job["jobId"],
        "updatedOn": datetime.datetime.now(),
        "status": status,
    }
    logger.info("job updated")
    job_collection.update_one(myQuery, {"$set": jobValue})
    return "job updated inserted"


def add_to_queue(filename, registerId, logisticsType, actualfile, documentId):
    if len(documentId) == 0:
        job = {
            "jobId": str(uuid.uuid1()).split('-')[0],
            "documentId": str(uuid.uuid1()).split('-')[0],
            "path": os.path.join(UPLOAD_FOLDER, actualfile),
            "fileName": filename,
            "registerId": registerId,
            "logisticsType": logisticsType,
            "actualfile": actualfile
        }
        q.put(job)
    else:
        job = {
            "jobId": str(uuid.uuid1()).split('-')[0],
            "documentId": documentId,
            "path": os.path.join(UPLOAD_FOLDER, actualfile),
            "fileName": filename,
            "registerId": registerId,
            "logisticsType": logisticsType,
            "actualfile": actualfile
        }
        q.put(job)
    logger.info("job added to queue")
    x = insert_job(job)
    # print(x)
    # print(q.unfinished_tasks)
    # print(q.qsize())
    # for n in list(q.queue):
    #     print(n, end="\n")
    return job


def analyze_invoice():
    while True:
        try:
            item = q.get()
            if item is None:
                continue

            try:
                update_job(item, "Inprogress")
                check_failed = invoice_collection.find_one({'documentId': item['documentId']}, {'_id': 0})
                # for task in check_failed:
                #     print(task)
                print(check_failed)

                data = register_collection.find_one({'registerId': item['registerId']}, {'_id': 0})
                for i in range(len(data['logistics'])):
                    if data['logistics'][i]['logisticsType'] == item['logisticsType']:
                        labels = model_collection.find_one(
                            {'modelDocumentId': data['logistics'][i]['modelDocumentId']}, {'_id': 0})
                if check_failed is None:
                    invoice_details1 = {
                        'insertedOn': datetime.datetime.now(),
                        'documentId': item['documentId'],
                        'registerId': data['registerId'],
                        'modelDocumentId': labels['modelDocumentId'],
                        'logisticsType': item['logisticsType'],
                        'path': item['fileName'],
                        'fileName': item['fileName'],
                        'status': "Inprogress",
                        'analyzedResult': {}
                    }
                    invoice_collection.insert(invoice_details1)
                    print(data)
                    print(labels)
                else:
                    myQuery = {'documentId': item['documentId']}
                    invoice_details1 = {
                        'insertedOn': datetime.datetime.now(),
                        'documentId': item['documentId'],
                        'registerId': data['registerId'],
                        'modelDocumentId': labels['modelDocumentId'],
                        'logisticsType': item['logisticsType'],
                        'path': item['fileName'],
                        'fileName': item['fileName'],
                        'status': "Inprogress",
                        'analyzedResult': {}
                    }
                    invoice_collection.update_one(myQuery, {"$set": invoice_details1})
                    print(data)
                    print(labels)
                try:
                    Result = test_invoices(item, labels)
                except Exception as e:
                    print(e)
                    Result = 'Failed'
                print("++dddddddddddddddd++", Result)
                if Result == 'Failed':
                    update_job(item, "Failed")
                    invoice_details = {
                        'insertedOn': datetime.datetime.now(),
                        'documentId': item['documentId'],
                        'registerId': data['registerId'],
                        'modelDocumentId': labels['modelDocumentId'],
                        'logisticsType': item['logisticsType'],
                        'path': item['fileName'],
                        'fileName': item['fileName'],
                        'status': "Failed",
                        'analyzedResult': {}
                    }
                    invoice_collection.update_one({'documentId': item['documentId']}, {"$set": invoice_details})
                else:
                    update_job(item, "Success")
                    invoice_details = {
                        'insertedOn': datetime.datetime.now(),
                        'documentId': item['documentId'],
                        'registerId': data['registerId'],
                        'modelDocumentId': labels['modelDocumentId'],
                        'logisticsType': item['logisticsType'],
                        'path': item['fileName'],
                        'fileName': item['fileName'],
                        'status': "Success",
                        'analyzedResult': {}
                    }
                    invoice_details['analyzedResult'].update(Result)
                    invoice_collection.update_one({'documentId': item['documentId']}, {"$set": invoice_details})
                logger.info("invoice results inserted into mongo")
                    # invoice_collection.insert(invoice_details)
            except Exception as e:
                update_job(item, "Failed")
            finally:
                q.task_done()
        except queue.Empty:
            pass
        except:
            logging.exception('error while processing item')


@invoice_namespace.route('/<path:filename>')
class get_file(Resource):
    def get(self, filename):
        return send_from_directory(UPLOAD_FOLDER,
                                   filename)


@invoice_namespace.route(APIEndPoints.get_invoices)
class get_invoices(Resource):
    def get(self):
        try:
            if request.method == RequestMethods.GET:
                all_invoices = invoice_collection.find({}, {"_id": 0}).sort('insertedOn', pymongo.DESCENDING)
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }
                for task in all_invoices:
                    # print(task)
                    task['insertedOn'] = task['insertedOn'].strftime("%d-%b-%Y %I:%M %p")
                    data['data'].append(task)
                return jsonify(data)
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})

    @api.expect(upload_parser)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                # content = request.get_json()
                # print(UPLOAD_FOLDER)
                # print(request.files)
                imd = request.files
                registerId = request.form.get('registerId')
                logisticsType = request.form.get('logisticsType')
                print(registerId, logisticsType)
                finaldict = imd.to_dict(flat=False)
                # print(finaldict)
                x = finaldict['file']
                print(x)
                if 'file' not in request.files:
                    # flash('No file part')
                    return jsonify({"status": "No file"})
                file = request.files['file']
                for file in x:
                    print(file)
                    print(file.filename)
                    if file.filename == '':
                        flash('No selected file')
                        return redirect(request.url)
                    if file and allowed_file(file.filename):
                        filename = secure_filename(file.filename)
                        x = filename.split('.')
                        print(x[0])
                        file.save(os.path.join(UPLOAD_FOLDER, filename))

                        finalpdfname = x[0] + '.pdf'
                        img_path = os.path.join(UPLOAD_FOLDER, filename)
                        pdf_path = os.path.join(UPLOAD_FOLDER, finalpdfname)
                        image = Image.open(img_path)
                        pdf_bytes = img2pdf.convert(image.filename)
                        file = open(pdf_path, "wb")
                        file.write(pdf_bytes)
                        image.close()
                        file.close()
                        #
                        #
                        # image1 = Image.open(os.path.join(UPLOAD_FOLDER, filename))
                        # im1 = image1.convert('RGB')
                        # finalpdfname = x[0] + '.pdf'
                        # im1.save(os.path.join(UPLOAD_FOLDER, finalpdfname))
                    else:
                        return jsonify({"status": "Not supported file format"})
                documentId = ''
                job = add_to_queue(finalpdfname, registerId, logisticsType, filename, documentId)
                print(job)
                # download_file(os.path.join(UPLOAD_FOLDER, filename))
                logger.info("job added")
                t = Thread(target=analyze_invoice)
                t.start()

                return jsonify({"status": True, "message": "Upload successful", "jobId": job["jobId"]})
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.create_register)
class create_register(Resource):
    @api.expect(create_register)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                content = request.get_json()
                print(content)
                labelList = []
                registerId = str(uuid.uuid1()).split('-')[0]
                register_details = {
                    "registerName": content['registerName'],
                    "registerId": registerId,
                    "registerIconUrl": "",
                    "lastUpdatedTime": datetime.datetime.utcnow(),
                    "logistics": [
                        {"logisticsType": "Inbound",
                         "modelDocumentId": content['inboundModelId']
                         },
                        {
                            "modelDocumentId": content['outboundModelId'],
                            "logisticsType": "Outbound"
                        }
                    ]
                    # {
                    # "inbound": {
                    #     "modelDocumentId": content['inboundModelId']
                    # },
                    # "outbound": {
                    #     "modelDocumentId": content['outboundModelId']
                    # }
                    # }
                }
                register_collection.insert(register_details)
                return jsonify({"status": True, "message": "Register inserted successfully", "registerId": registerId})
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.retry_invoice)
class retry_invoice(Resource):
    @api.expect(retry_parser)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                # content = request.get_json()
                # documentId = request.form.get('documentId')
                imd = request.files
                documentId = request.form.get('documentId')
                registerId = request.form.get('registerId')
                logisticsType = request.form.get('logisticsType')
                finaldict = imd.to_dict(flat=False)
                # print(finaldict)
                x = finaldict['file']
                job_results = job_collection.find({'documentId': documentId}, {"_id": 0})
                print(x)
                if 'file' not in request.files:
                    # flash('No file part')
                    return jsonify({"status": "No file"})
                file = request.files['file']
                for file in x:
                    print(file)
                    print(file.filename)
                    if file.filename == '':
                        flash('No selected file')
                        return redirect(request.url)
                    if file and allowed_file(file.filename):
                        filename = secure_filename(file.filename)
                        x = filename.split('.')
                        print(x[0])
                        file.save(os.path.join(UPLOAD_FOLDER, filename))

                        finalpdfname = x[0] + '.pdf'
                        img_path = os.path.join(UPLOAD_FOLDER, filename)
                        pdf_path = os.path.join(UPLOAD_FOLDER, finalpdfname)
                        image = Image.open(img_path)
                        pdf_bytes = img2pdf.convert(image.filename)
                        file = open(pdf_path, "wb")
                        file.write(pdf_bytes)
                        image.close()
                        file.close()
                        #
                        #
                        # image1 = Image.open(os.path.join(UPLOAD_FOLDER, filename))
                        # im1 = image1.convert('RGB')
                        # finalpdfname = x[0] + '.pdf'
                        # im1.save(os.path.join(UPLOAD_FOLDER, finalpdfname))
                    else:
                        return jsonify({"status": "Not supported file format"})

                job = add_to_queue(finalpdfname, registerId, logisticsType, filename, documentId)
                # print(job)
                # download_file(os.path.join(UPLOAD_FOLDER, filename))
                logger.info("job added")
                t = Thread(target=analyze_invoice)
                t.start()

                return jsonify({"status": True, "message": "Upload successful", "jobId": job["jobId"]})
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.list_register)
class list_register(Resource):
    def get(self):
        try:
            if request.method == RequestMethods.GET:
                all_registers = register_collection.find({}, {"_id": 0})
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }
                for task in all_registers:
                    # print(task)
                    task['lastUpdatedTime'] = task['lastUpdatedTime'].strftime("%d-%b-%Y %I:%M %p")
                    data['data'].append(task)
                return jsonify(data)
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.create_model)
class create_model(Resource):
    @api.expect(create_model)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                content = request.get_json()
                modelDocumentId = str(uuid.uuid1()).split('-')[0]
                # print(content)
                labelList = []
                model_details = {
                    "modelDocumentId": modelDocumentId,
                    "modelId": content['modelId'],
                    "createdDateTime": datetime.datetime.utcnow(),
                    "lastUpdatedDateTime": datetime.datetime.utcnow(),
                    "trainedDocuments": int(content['trainedDocuments']),
                    "trainedLabels": content['trainedLabels']
                }
                model_collection.insert(model_details)
                return jsonify(
                    {"status": True, "message": "Model registered successfully", "modelDocumentId": modelDocumentId})
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.list_model)
class list_model(Resource):
    def get(self):
        try:
            if request.method == RequestMethods.GET:
                all_models = model_collection.find({}, {"_id": 0})
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }
                for task in all_models:
                    # print(task)
                    data['data'].append(task)
                return jsonify(data)
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.get_job_status)
class get_job_status(Resource):
    @api.expect(get_job_status)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                content = request.get_json()
                # all_jobs = job_collection.find({'jobId': content['jobId']}, {"_id": 0})
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }
                for i in content['jobId']:
                    all_jobs = job_collection.find({'jobId': i}, {"_id": 0})
                    for task in all_jobs:
                        # print(task)
                        data['data'].append(task)

                return jsonify(data)
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})

    def get(self):
        try:
            if request.method == RequestMethods.GET:
                all_jobs = job_collection.find({}, {"_id": 0})
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }
                for task in all_jobs:
                    # print(task)
                    data['data'].append(task)
                return jsonify(data)
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.invoices_for_register)
class invoices_for_register(Resource):
    @api.expect(invoices_for_register)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                content = request.get_json()
                all_invoices = invoice_collection.find({'registerId': content['registerId']}, {"_id": 0})
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }
                for task in all_invoices:
                    # print(task)
                    task['timestamp'] = task['insertedOn'].strftime("%d-%b-%Y %I:%M %p")
                    data['data'].append(task)
                return jsonify(data)
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.searchOn)
@api.doc(params={'label': 'label', 'value': 'value'})
class searchOn(Resource):
    def get(self):
        if request.method == 'GET':
            try:
                label = request.args.get('label', "")
                value = request.args.get('value', "")
                # registerId = request.args.get('registerId', "")
                search_list = invoice_collection.find({}, {'_id': 0})
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }

                for task in search_list:
                    # print(task['analyzedResult'][str(label)])
                    # print(len(task['analyzedResult']))
                    for key in task['analyzedResult']:
                        if key == str(label):
                            if task['analyzedResult'][key] == str(value):
                                task['timestamp'] = task['insertedOn'].strftime("%d-%b-%Y %I:%M %p")
                                data['data'].append(task)

                return jsonify(data)
            except Exception as e:
                logger.info(e)
                return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.get_invoice_result)
class get_invoice_result(Resource):
    @api.expect(get_invoice_result)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                content = request.get_json()
                all_results = invoice_collection.find({'documentId': content['documentId']}, {"_id": 0})
                data = {
                    "status": True,
                    "message": "success",
                    "data": [

                    ]
                }

                for task in all_results:
                    # print(task)
                    task['insertedOn'] = task['insertedOn'].strftime("%d-%b-%Y %I:%M %p")
                    data['data'].append(task)
                return jsonify(data)
        except Exception as e:
            logger.error(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.download_report)
class download_report(Resource):
    @api.expect(download_report)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                try:
                    content = request.get_json()
                    file = open("data/report.csv", "w")
                    file.close()
                    field_names = ['analyzedResult', 'insertedOn', 'documentId', 'registerId',
                                   'modelDocumentId', 'logisticsType', 'path', 'fileName']
                    field_names1 = ['Register', 'RegisterType', 'File Name', 'From', 'Invoice Date', 'Invoice No',
                                    'Motor Vehicle No', 'Quantity', 'Docket No']
                    with open("data/report.csv", 'a+', newline='') as file:
                        writer = csv.writer(file)
                        writer.writerow(field_names1)
                    data = {
                        "status": True,
                        "message": "success",
                        "data": [

                        ]
                    }
                    register = ""
                    from_date = content.get('fromDate', str(datetime.datetime.now().date().isoformat()))
                    to_date = content.get('toDate', str(datetime.datetime.now().date().isoformat()))
                    from_date = datetime.datetime.strptime(from_date + "T00:00:00.100Z", '%d/%m/%YT%H:%M:%S.%fZ')
                    to_date = datetime.datetime.strptime(to_date + "T23:59:59.100Z", '%d/%m/%YT%H:%M:%S.%fZ')
                    # print(from_date.isoformat())
                    toEmail = content['toEmail']
                    registerIdList = content['registerIdList']
                    print(from_date, to_date, toEmail, registerIdList)
                    for i in registerIdList:
                        print(i)
                        total_invoices = invoice_collection.find(
                            {'registerId': i, "insertedOn": {"$gte": from_date, "$lt": to_date}},
                            {"_id": 0}).sort('insertedOn', pymongo.DESCENDING)
                        registernames = register_collection.find_one({'registerId': i}, {"_id": 0})
                        register = register + ' ' + registernames['registerName'] + ', '
                        for task in total_invoices:
                            # print(task)
                            task['insertedOn'] = task['insertedOn'].strftime("%d-%b-%Y %I:%M %p")

                            for key in task['analyzedResult']:
                                sendjosn = {'Register': registernames['registerName'],
                                            'RegisterType': task['logisticsType'], 'File Name': task['fileName'],
                                            'From': "",
                                            'Invoice Date': "", 'Invoice No': "",
                                            'Motor Vehicle No': "",
                                            'Quantity': "", 'Docket No': ""}
                                if len(task['analyzedResult']) == 2:
                                    sendjosn['From'] = task['analyzedResult']['From']
                                    sendjosn['Docket No'] = task['analyzedResult'][key]


                                else:
                                    sendjosn['From'] = task['analyzedResult']['From']
                                    sendjosn['Invoice Date'] = task['analyzedResult']['Invoice Date']
                                    sendjosn['Invoice No'] = task['analyzedResult']['Invoice No']
                                    sendjosn['Motor Vehicle No'] = task['analyzedResult']['Motor Vehicle No']
                                    sendjosn['Quantity'] = task['analyzedResult']['Quantity']
                                    # append_dict_as_row('data/report.csv', sendjosn, field_names1)
                            # append_dict_as_row('data/report.csv', task, field_names)
                            append_dict_as_row('data/report.csv', sendjosn, field_names1)
                            data['data'].append(task)
                    # pdf_file = generate_pdf_report(from_date, to_date, eventtype)
                    # return send_file(pdf_file,
                    #                  as_attachment=True)

                    # Python code to illustrate Sending mail with attachments
                    # from your Gmail account

                    # libraries to be imported

                    fromaddr = "dasharatha.vamshi@knowledgelens.com"
                    toaddr = toEmail
                    msg = MIMEMultipart()
                    msg['From'] = fromaddr
                    msg['To'] = toaddr
                    msg['Subject'] = "Report Generated"
                    body = "Please find the report generated for " + register + " between " + content[
                        'fromDate'] + " and " + content['toDate']

                    msg.attach(MIMEText(body, 'plain'))
                    filename = "report.csv"
                    attachment = open("data/report.csv", "rb")
                    p = MIMEBase('application', 'octet-stream')
                    p.set_payload((attachment).read())
                    encoders.encode_base64(p)
                    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
                    msg.attach(p)
                    s = smtplib.SMTP('smtp.gmail.com', 587)
                    s.starttls()
                    s.login(fromaddr, "Salla$230999")
                    text = msg.as_string()
                    s.sendmail(fromaddr, toaddr, text)
                    s.quit()
                    # receiver = toEmail
                    # body = "Pls find attached document"
                    # filename = "data/report.csv"
                    #
                    # yag = yagmail.SMTP("dasharatha.vamshi@knowledgelens.com")
                    # yag.send(
                    #     to=receiver,
                    #     subject="Report Generated",
                    #     contents=body,
                    #     attachments=filename,
                    # )
                    print(len(data['data']))
                    send_mail = jsonify(data)
                    print(data)
                    return jsonify({'status': True, 'message': "Email Sent"})
                except Exception as e:
                    logger.info(e)
                    traceback.print_exc()
                    return jsonify({'status': False, 'message': str(e)})
        except Exception as e:
            logger.info(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})


@invoice_namespace.route(APIEndPoints.register_details)
class register_details(Resource):
    @api.expect(register_details)
    def post(self):
        try:
            if request.method == RequestMethods.POST:
                try:
                    content = request.get_json()
                    data = {
                        "status": True,
                        "message": "success",
                        "data": [

                        ]
                    }

                    all_register = register_collection.find({'registerId': content['registerId']}, {"_id": 0})
                    A = []

                    for task in all_register:
                        print(task)

                        for i in task['logistics']:
                            append = {"files": [], 'typeTitle': i['logisticsType'],
                                      'lastUpdatedTime': task["lastUpdatedTime"].strftime("%d-%b-%Y %I:%M %p")}
                            all_invoices = invoice_collection.find(
                                {'registerId': content['registerId'], 'logisticsType': i['logisticsType']},
                                {"_id": 0}).sort('insertedOn', pymongo.DESCENDING)
                            for j in all_invoices:
                                j['insertedOn'] = j['insertedOn'].strftime("%d-%b-%Y %I:%M %p")
                                append['files'].append(j)
                            data['data'].append(append)

                    return jsonify(data)
                except Exception as e:
                    logger.info(e)
                    traceback.print_exc()
                    return jsonify({'status': False, 'message': str(e)})
        except Exception as e:
            logger.info(e)
            traceback.print_exc()
            return jsonify({'status': False, 'message': str(e)})
