#!/usr/bin/env python
# coding: utf-8

# # Google Keep API

# In[63]:


import gkeepapi
from jinja2 import Template


# In[2]:


import os
import json


# In[4]:


keep = gkeepapi.Keep()
keep.login(os.environ["GOOGLE_EMAIL"], os.environ["GOOGLE_PASS"])


# In[51]:


# get journal notes
notes = keep.find(labels=[keep.findLabel('journal')])
journal_notes = sorted(notes, key=lambda x: x.timestamps.created)


# In[55]:


# get last weekly review
gnotes = list(keep.find(labels=[keep.findLabel('journal-weekly')]))
gnotes = sorted(gnotes, key=lambda x: x.timestamps.created, reverse=True)
last_weekly_note = gnotes[0] if gnotes else None

# if no weekly review, process all journal notes
start_date_for_review = last_weekly_note.timestamps.created if last_weekly_note else journal_notes[0].timestamps.created

notes_to_review = [last_weekly_note] if last_weekly_note else []
notes_to_review = notes_to_review + list(filter(lambda note: note.timestamps.created >= start_date_for_review, journal_notes))


# In[108]:


template_html = '''
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

     <title>Weekly review!</title>
  </head>
  <body>


    <h1>Time for your weekly review!</h1>

    {% for note in notes %}
    <h2> {{ note.timestamps.created.date().__str__() }} </h2>
    <h3> {{ note.title }} </h3>
    {% for paragraph in note.text.splitlines() %}
    <p> {{ paragraph }} </p>
    {% endfor %}
    <hr>

    {% endfor %}

  </body>
</html>

'''


# In[109]:


template = Template(template_html)
out_html = template.render(week_text='John Doe', notes=notes_to_review)


# # sending email with gmail

# In[113]:


import smtplib, ssl

from email.mime.text import MIMEText 
from email.mime.multipart import MIMEMultipart 

port = 465  
smtp_server = "smtp.gmail.com"
login = os.environ["GOOGLE_EMAIL"] # paste your login generated by Mailtrap 
password =  os.environ["GOOGLE_PASS"] # paste your password generated by Mailtrap
sender_email = os.environ["GOOGLE_EMAIL"]
receiver_email = os.environ["GOOGLE_EMAIL"] 
message = MIMEMultipart("alternative") 
message["Subject"] = "Weekly review" 
message["From"] = sender_email 
message["To"] = receiver_email 

# convert both parts to MIMEText objects and add them to the MIMEMultipart message 
part2 = MIMEText(out_html, "html") 
message.attach(part2)
 
try:
    #send your message with credentials specified above
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        print("created server")
        server.login(login, password)
        print("logged in")
        server.sendmail( sender_email, receiver_email, message.as_string() ) 
        print("sent")
except (gaierror, ConnectionRefusedError):
    print('Failed to connect to the server. Bad connection settings?')
except smtplib.SMTPServerDisconnected:
    print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
    print('SMTP error occurred: ' + str(e))

