import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import warnings

warnings.filterwarnings("ignore")

df = pd.read_csv('Data/MaintainData.csv')
#df = df.groupby('mailID')

#df = pd.DataFrame(df['Customer'].unique())

df['a'] = pd.to_datetime(df['Date']).diff()
df['a'] = df['a'].astype(str).str.replace("days", "")
df['a'] = df['a'].astype(str).str.replace("NaT", "30")
df = df[(df["mailID"] == 'nbachalaka@gmail.com')]
X = df[['TakenTime', 'Price', 'MeterReading']]
y = df['a']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

logreg = LogisticRegression()
logreg.fit(X_train, y_train)
Accuracy = logreg.score(X_test, y_test)

MeterReading = df['MeterReading'].mean()
TakenTime = df['TakenTime'].mean()
Price = df['Price'].mean()

print(Price)
new_input = [[TakenTime, Price, MeterReading]]
pred = logreg.predict(X)
# print(pred)

# Assign predicted Dates to datafram
se = pd.Series(pred)
df['new_col'] = se.values


df['Date'] = pd.to_datetime(df['Date'])
df['ComesON'] = df['Date'] + pd.to_timedelta(df['new_col'].astype(int), unit='D')
print(df)

# Get Today Date
from datetime import date
today = date.today()
print(today)
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print(d1)
# 3 days before predicted date
enddate = pd.to_datetime(d1) - pd.DateOffset(days=3)

print(enddate)
# print(enddate.strftime("%d/%m/%Y"))



finalDate = enddate.strftime("%d/%m/%Y")
# df = df[(df["ComesON"] == finalDate)]
print(df)
PredictedMails = df["mailID"].tolist()
#print(PredictedMails)



# mail server
import smtplib
gmail_user = 'chalakasliit@gmail.com'
gmail_password = 'SLIIT2022%'

sent_from = gmail_user
to = PredictedMails # customer mails
subject = 'Reminder about Your Vehicle Service'
body = 'Still 3 Days for your Vehicle service!'

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

    print("Email sent")
except:
    print("No services available...")

# mail server



