#!/usr/bin/python3
import gspread
import smtplib
import ssl
import imapclient
import os
import email
import sys
import re
import time

from docx import Document
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from Input import Input
from Parse import Parse

directories = []
senders = []
candidate_list = []
doc_name = 'Candidate Tracker'
error = ''
        
def sheet_connect():
    """
    Function connects to google API and spreadsheet using credentials via JSON file and gpsread module and creates a 
    working set of sheets to read and write to
    """
    global error
    
    try:
        from oauth2client.service_account import ServiceAccountCredentials
        scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
        creds = ServiceAccountCredentials.from_json_keyfile_name('/home/pi/Desktop/Python/Bot/bot_cred.json', scope)
        client = gspread.authorize(creds)
        doc = client.open(doc_name)
        
        #Returns a list of sheets to work from within the spreadsheet file
        global sheet_list
        sheet_list = doc.worksheets()
        
    except:
        error = 'Unable to connect to spreadsheet'
        send_error()
  
  
def send_error():
    """
    Function to retreive error variable and deliver email to master and provide error notification and information
    """
  
    pw = ''
    sent_from = ''
    to = ''
    subject = 'Error'
    body = error
    msg = MIMEMultipart()
    msg['To'] =''.join(to)
    msg['From'] = sent_from
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sent_from, pw)
        server.sendmail(sent_from, to, msg.as_string())
    print('Error detected: ', error + '.', 'Closing program.')
    exit()
    
        
def send_email(sender):
    """
    Function to notify sender via email that request has been recieved and spreadsheet updated
    """
    
    password = ''
    sent_from = ''
    to = sender
    subject = ('Request received. Tracker updated.') 
    body = ' '
    msg = MIMEMultipart()
    msg['To'] =''.join(to)
    msg['From'] = sent_from
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))

    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sent_from, password)
        server.sendmail(sent_from, to, msg.as_string())

"""
Initialize Parse class and Main class. Run email search method to search for emails, then run main code. If the 
Parse class found any emails with indicated subject and attachments, Parse passes True to run() indicating it to run 
its full length and analyze the attachments; otherwise, run exits without executing. 
"""

print('Executing program...')
bot = ParseBot()
bot.email_search()
run = Main()
run.run()















