import requests
from twilio.rest import Client

import smtplib
from email.message import EmailMessage

# VIRTUAL_TWILIO_NUMBER = "+15182031319"
# VERIFIED_NUMBER = "+62895376344510"

STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"

STOCK_API_KEY = "L817NBW6VKH5Q7PQ"
NEWS_API_KEY = "16188f18380b40d0ba0acd218fb36b74"

FROM_EMAIL: 'nihaopython21@gmail.com'
TO_EMAIL: 'nihaopython21@gmail.com'
PASSWORD: 'helloPython!9'

# TWILIO_SID = "AC27890497598e53480d3dd9d201c45845"
# TWILIO_AUTH_TOKEN = "c566fc2914b0b95671f41d8e27561a26"

    ## STEP 1: Use https://www.alphavantage.co/documentation/#daily
# When stock price increase/decreases by 5% between yesterday and the day before yesterday then print("Get News").

#TODO 1. - Get yesterday's closing stock price. Hint: You can perform list comprehensions on Python dictionaries. e.g. [new_value for (key, value) in dictionary.items()]
stock_params = {
    "function": "TIME_SERIES_DAILY",
    "symbol": STOCK_NAME,
    "apikey": STOCK_API_KEY,
}

response = requests.get(STOCK_ENDPOINT, params=stock_params)
data = response.json()["Time Series (Daily)"]
data_list = [value for (key, value) in data.items()]
yesterday_data = data_list[0]
yesterday_closing_price = yesterday_data["4. close"]
print(yesterday_closing_price)

#TODO 2. - Get the day before yesterday's closing stock price
day_before_yesterday_data = data_list[1]
day_before_yesterday_closing_price = day_before_yesterday_data["4. close"]
print(day_before_yesterday_closing_price)

#TODO 3. - Find the positive difference between 1 and 2. e.g. 40 - 20 = -20, but the positive difference is 20. Hint: https://www.w3schools.com/python/ref_func_abs.asp
difference = float(yesterday_closing_price) - \
    float(day_before_yesterday_closing_price)
up_down = None
if difference > 0:
    up_down = "🔺"
else:
    up_down = "🔻"

#TODO 4. - Work out the percentage difference in price between closing price yesterday and closing price the day before yesterday.
diff_percent = round((difference / float(yesterday_closing_price)) * 100)
print(diff_percent)

    ## STEP 2: https://newsapi.org/ 
    # Instead of printing ("Get News"), actually get the first 3 news pieces for the COMPANY_NAME. 

#TODO 6. - Instead of printing ("Get News"), use the News API to get articles related to the COMPANY_NAME.
if abs(diff_percent) > 0.5:
    news_params = {
        "apiKey": NEWS_API_KEY,
        "qInTitle": COMPANY_NAME,
    }

    news_response = requests.get(NEWS_ENDPOINT, params=news_params)
    articles = news_response.json()["articles"]

#TODO 7. - Use Python slice operator to create a list that contains the first 3 articles. Hint: https://stackoverflow.com/questions/509211/understanding-slice-notation
    three_articles = articles[:3]
    print(three_articles)

    ## STEP 3: Use twilio.com/docs/sms/quickstart/python
    #to send a separate message with each article's title and description to your phone number. 

# #TODO 8. - Create a new list of the first 3 article's headline and description using list comprehension.
#     formatted_articles = [
#         f"{STOCK_NAME}: {up_down}{diff_percent}%\nHeadline: {article['title']}. \nBrief: {article['description']}" for article in three_articles]
#     print(formatted_articles)
# #TODO 9. - Send each article as a separate message via Twilio. 
#     client = Client(TWILIO_SID, TWILIO_AUTH_TOKEN)

# #TODO 10. - Send each article as a separate message via Twilio.
#     for article in formatted_articles:
#         message = client.messages.create(
#             body=article,
#             from_=VIRTUAL_TWILIO_NUMBER,
#             to=VERIFIED_NUMBER
#         )

    for article in three_articles:
        subject = f"{STOCK_NAME}:{up_down}{diff_percent}% ,{article['title']}"
        body = f"{article['description']}"
        message = EmailMessage()
        message.add_header("From", 'nihaopython21@gmail.com')
        message.add_header("To", 'nihaopython21@gmail.com')
        message.add_header("Subject", 'ALERT NEWS!!!')
        message.set_payload(body, "utf-8")
        with smtplib.SMTP("smtp.gmail.com", port=587) as connection:
            connection.starttls()
            connection.login(user='nihaopython21@gmail.com', password='helloPython!9')
            connection.send_message(
                message, from_addr='nihaopython21@gmail.com', to_addrs='nihaopython21@gmail.com')



#Optional TODO: Format the message like this: 
"""
TSLA: 🔺2%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. 
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
or
"TSLA: 🔻5%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. 
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
"""

