from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import time
import gc
import gzip
import shutil
import numpy as np
import re

from scipy import optimize

import rowingdata

from rowingdata import rowingdata as rdata

from celery import app
import datetime
import pytz
import iso8601

from matplotlib.backends.backend_agg import FigureCanvas
#from matplotlib.backends.backend_cairo import FigureCanvasCairo as FigureCanvas
import matplotlib.pyplot as plt

from rowsandall_app.settings import SITE_URL
from rowsandall_app.settings_dev import SITE_URL as SITE_URL_DEV
from rowsandall_app.settings import PROGRESS_CACHE_SECRET
from rowsandall_app.settings import SETTINGS_NAME


import pandas as pd

from django_rq import job
from django.utils import timezone
from django.utils.html import strip_tags

from django.core.mail import (
    send_mail,
    EmailMessage,EmailMultiAlternatives,
    )

from django.template import Context
from django.db.utils import OperationalError
from jinja2 import Template,Environment,FileSystemLoader
env = Environment(loader = FileSystemLoader(["rowers/templates"]))

from django.contrib.staticfiles import finders



def textify(html):
    # Remove html tags and continuous whitespaces 
    text_only = re.sub('[ \t]+', ' ', strip_tags(html))
    # Strip single spaces in the beginning of each line
    return text_only.replace('\n ', '\n').strip()

def htmlstripnobr(html):
    safe_html = re.sub('[ \t]+', ' ', strip_tags(html))
    return safe_html
    
def htmlstrip(html):
    safe_html = re.sub('[ \t]+', ' ', strip_tags(html))
    return newlinetobr(safe_html)

def newlinetobr(html):
    html =  html.replace('\n\n','<br>')
    return html.replace('\n','<br>')

def send_template_email(from_email,to_email,subject,
                        template,context,
                        *args,**kwargs):

    htmly = env.get_template(template)

    html_content = htmly.render(context)
    text_content = textify(html_content)
    #    html_content = newlinetobr(html_content)

    if 'cc' in kwargs:
        msg = EmailMultiAlternatives(subject, text_content, from_email, to_email,cc=kwargs['cc'])
    else:
        msg = EmailMultiAlternatives(subject, text_content, from_email, to_email)
        
    msg.attach_alternative(html_content, "text/html")

    if 'attach_file' in kwargs:
        fileobj = kwargs['attach_file']
        if os.path.isfile(fileobj):
            msg.attach_file(fileobj)
        else:
            try:
                fileobj2 = fileobj
                with gzip.open(fileobj+'.gz','rb') as f_in, open(fileobj2,'wb') as f_out:
                    shutil.copyfileobj(f_in,f_out)
                msg.attach_file(fileobj2)
                os.remove(fileobj2)
            except IOError:
                pass

    if 'emailbounced' in kwargs:
        emailbounced = kwargs['emailbounced']
    else:
        emailbounced = False

        
        
    if not emailbounced:
        res = msg.send()
    else:
        return 0

    return res
