from flask import Flask, render_template, request, redirect, abort
import os
import watchlist
import stock
import datetime as dt
import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from collections import OrderedDict

ROOTDIR = os.path.abspath(os.curdir)

app = Flask(__name__, template_folder='templates')
companies = ['AAPL', 'SPY', 'MSFT', 'BTC-USD', 'ETH-USD', 'TSLA', 'BITI.TO', 'META', 'GOOG', 'AMZN']
charts = ['1W', '1M', '3M', '1Y']
# stock_responses = {}

# @app.route('/')
# def home():
#     # return render_template('index.html', result = watchlist_result())
#     return redirect("/test2")

# @app.route('/test')
# def test():
#     file_to_open = os.path.join(ROOTDIR, 'market_data', 'aapl' + '.csv')
#     data = pd.read_csv(file_to_open, parse_dates=True, skipinitialspace=False)
#     del data['Adj Close']
#     df = data.round(2).sort_values('Date', ascending=False)
#     return render_template('test.html', companies=companies, result = watchlist_result(), tables=[df.to_html(index=False)], titles=[''])

@app.route('/')
def test2():
    stock_responses = watchlist.get_stocks(companies)
    stock_prices = watchlist.get_current_prices(companies, stock_responses)
    watchlist.save_historical_data(companies[0])
    df = get_dataframe(companies[0])
    create_charts(companies[0])
    return render_template('test.html', company=companies[0], companies=companies, charts=charts, result = OrderedDict(sorted(stock_prices.items())), tables=[df.to_html(index=False)], titles=[''])

def get_dataframe(company):
    file_to_open = os.path.join(ROOTDIR, 'market_data', company + '.csv')
    data = pd.read_csv(file_to_open, parse_dates=True, skipinitialspace=False)
    del data['Adj Close']
    df = data.round(2).sort_values('Date', ascending=False)
    return df

def create_charts(company):
    file_to_open = os.path.join(ROOTDIR, 'market_data', company + '.csv')
    # png_to_save = os.path.join(ROOTDIR, 'static', company + '.png')
    df = pd.read_csv(file_to_open, parse_dates=True, skipinitialspace=False)
    df = df.sort_values('Date')
    df.index = pd.DatetimeIndex(df['Date'])
    plt.switch_backend('agg')

    current_date = dt.datetime.now()
    formatted_current_date = current_date.strftime('%Y-%m-%d')

    formatted_one_week_ago = (current_date - dt.timedelta(days=7)).strftime('%Y-%m-%d')
    formatted_one_month_ago = (current_date - dt.timedelta(days=30)).strftime('%Y-%m-%d')
    formatted_three_month_ago = (current_date - dt.timedelta(days=90)).strftime('%Y-%m-%d')
    formatted_one_year_ago = (current_date - dt.timedelta(days=365)).strftime('%Y-%m-%d')
    try:
        # One Week Candlestick Chart
        tdf = df.loc[formatted_one_week_ago:formatted_current_date,:]
        mpf.plot(tdf, type='candlestick', style='yahoo', volume=True, title=company, tight_layout=True, figsize=(16,8), savefig=os.path.join(ROOTDIR, 'static', company + '_1w.png'))
        # One Month Candlestick Chart
        tdf = df.loc[formatted_one_month_ago:formatted_current_date,:]
        mpf.plot(tdf, type='candlestick', style='yahoo', volume=True, title=company, tight_layout=True, figsize=(16,8), savefig=os.path.join(ROOTDIR, 'static', company + '_1m.png'))
        # Three Month Candlestick Chart
        tdf = df.loc[formatted_three_month_ago:formatted_current_date,:]
        mpf.plot(tdf, type='candlestick', style='yahoo', volume=True, title=company, tight_layout=True, figsize=(16,8), savefig=os.path.join(ROOTDIR, 'static', company + '_3m.png'))
        # One Year Candlestick Chart
        tdf = df.loc[formatted_one_year_ago:formatted_current_date,:]
        mpf.plot(tdf, type='candlestick', style='yahoo', volume=True, title=company, tight_layout=True, figsize=(16,8), savefig=os.path.join(ROOTDIR, 'static', company + '_1y.png'))
    except Exception as e:
        print(e)
        pass

# def create_charts2(company):
#     file_to_open = os.path.join(ROOTDIR, 'market_data', company + '.csv')
#     df = pd.read_csv(file_to_open, parse_dates=True, skipinitialspace=False)
#     df = df.sort_values('Date')
#     df.index = pd.DatetimeIndex(df['Date'])

#     current_date = dt.datetime.now()
#     formatted_current_date = current_date.strftime('%Y-%m-%d')

#     try:
#         plt.switch_backend('agg')
#         png_to_save = os.path.join(ROOTDIR, 'static', company + '.png')
#         plt.figure(figsize = (12,6))
#         plt.plot(range(df.shape[0]),(df['Low']+df['High'])/2.0)
#         plt.xticks(range(0,df.shape[0],500),df['Date'].loc[::500],rotation=45)
#         plt.xlabel('Date',fontsize=18)
#         plt.ylabel('Mid Price',fontsize=18)
#         plt.title(company, fontsize=26)
#         plt.savefig(png_to_save)
#     except Exception as e:
#         print(e)
#         pass

# @app.route('/about')
# def about():
#     return render_template('about.html')

# @app.route('/1y/<ticker>')
# def one_year(ticker):
#     watchlist.get_historical_data(str, "1y")
#     stock.get_chart(str)
#     return render_template('yearly.html', ticker = ticker)
#     # return ('', 200)
#     # return redirect("/")

# @app.route('/table')
# def table():
#     file_to_open = os.path.join(ROOTDIR, 'market_data', 'aapl' + '.csv')
#     data = pd.read_csv(file_to_open, parse_dates=True, skipinitialspace=False)
#     del data['Adj Close']
#     df = data.round(2).sort_values('Date', ascending=False)
#     print(df)
#     return render_template('table.html', tables=[df.to_html(index=False)], titles=[''])

# @app.route('/predict')
# def predict():
#     file_to_open = os.path.join(ROOTDIR, 'market_data', 'aapl' + '.csv')
#     data = pd.read_csv(file_to_open, parse_dates=True, skipinitialspace=False)
#     print(data)
#     # df = data.sort_values('Date', ascending=False)
#     df = data.sort_values('Date')
#     del df['Adj Close']
#     print(df.describe())

#     return render_template('table.html', tables=[df.to_html(index=False)], titles=[''])

@app.route('/ticker/')
def ticker():
    if request.args.get('symbol'):
        symbols = request.args.get('symbol').strip().split(" ")
        for stock in reversed(symbols):
            stock = stock.strip().upper()
            if not stock:
                continue
            if stock in companies:
                companies.remove(stock)
            companies.insert(0, stock)
            if len(companies) > 10:
                companies.pop(10)
    return redirect("/")
    # return render_template('index.html', result = watchlist_result())


# @app.route('/ticker/<str>/')
# def ticker(str):
#     print(str)
#     return '<p>Ticker: %s</p>'%(str)

# @app.route('/watchlist/', methods = ['GET', 'POST'])
# def watchlist_result():
#     match request.method:
#         case 'GET':
#             return watchlist.get_watchlist_prices(companies)
#         case 'POST':
#             pass
#             # do something

# @app.route("/ticker/<str1>/<str2>/")
# def two_tickers(str1, str2):
#     return '<p>Ticker 1:%s</p> <p>Ticker 2:%s</p>'%(str1, str2)

# @app.route("/ticker/<str1>/<str2>/<str3>/")
# def three_tickers(str1, str2, str3):
#     return '<p>Ticker 1:%s</p><p>Ticker 2:%s</p> <p>Ticker 3:%s</p>'%(str1, str2, str3)

# @app.route('/users/<int:user_id>/')
# def greet_user(user_id):
#     users = ['Bob', 'Jane', 'Adam']
#     try:
#         return '<h2>Hi {}</h2>'.format(users[user_id])
#     except IndexError:
#         abort(404)
    
if __name__ == "__main__":
    app.run(debug=True)

# Tutorial
# https://www.digitalocean.com/community/tutorials/how-to-create-your-first-web-application-using-flask-and-python-3