# Copyright (C) 2021 Neythen Treloar neythen@fintic.io
#
# This file is part of stockTicker project for justinodunn.
#
# stockTicker can not be copied and/or distributed without the express
# permission of Neythen Treloar

from PIL import Image
from flask import Flask, render_template, request
from stockTicker import StockTicker
from werkzeug.utils import secure_filename
import os
import pytz
import datetime
from datetime import timedelta
import threading
import csv
import pexpect
import time
import json
from multiprocessing import Process
import subprocess
from subprocess import Popen, PIPE
import numpy as np
import copy
import urllib.request
import sys
#stock_ticker = StockTicker()
import traceback
import requests

#open('log.txt', 'w').close() #wipe logs 


#api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 api_caller.py")
#api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 database_caller.py")
#time.sleep(3)


#api_caller.sendline('A')


#pexpect.spawn("./check_update.sh")

displaying_screensaver = False
uploading = False
screensaver_p = None 
ticker_stopped = False

try:
    f = open('csv/display_settings.json', 'r')
    professional = json.load(f)[0] == "Professional"
    f.close()
except:
    professional = False

command = 300
tickerList = 0
DelayTime = 20
LastCommand = ''
speedTime = 25 

LOGO_FOLDER = 'logos/'
CSV_FOLDER = 'csv/new/'
ALLOWED_EXTENSIONS = {'csv', 'png'}

ticker = pexpect.spawn("sudo -E python3 -W ignore stockTicker.py")
time.sleep(2) # give the ticker time to initialise 


try:
    f = open('csv/system_info.json', 'r')
    system_info = json.load(f)
except Exception as e:
    system_info = {"update_available": False, "first_boot": False}
    f = open('csv/system_info.json', 'w')
    json.dump(system_info, f)
    system_info = json.load(f)
f.close()
             
ticker.sendline('*') # run startup gif by default 
time.sleep(8)
if system_info['first_boot']: # let startup message display 
    
    ticker.sendline('-')
    system_info['first_boot'] = False
    f =  open('csv/system_info.json', 'w')
    json.dump(system_info,f)
    f.close()
else:
    ticker.sendline('A') # run by default 

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def process_file(path, filename):
    default_csv = csv.writer(open('csv/tickers.csv', 'w+'))
    new_csv = csv.reader(open((path), 'r'))

    for row in new_csv:
        default_csv.writerow(row)

class DummyProcess():
    def close(self):
        return True

    
# try:
#     f = open('csv/last_updates.json', 'r')
#     last_updates = json.load(f)
#     f.close()
#     last_updates['stocks']['force'] = True
#     #last_updates['weather']['force'] = True
#     f = open('csv/last_updates.json', 'w')
#     json.dump(last_updates, f)
#     f.close()  
# except:
#     pass


# output = subprocess.check_output(['sudo', 'iwlist', 'wlan0', 'scan'])
# output_str = output.decode('utf-8')
# lines = output_str.split('Cell')

networks = {}

# for line in lines:
#     if 'ESSID:""\n' not in line and 'Scan completed' not in line:
#         ssid = line.split('ESSID:')[1].split('\n')[0]
#         ssid = ssid.replace('"', '', 1)
#         ssid = ssid[::-1].replace('"', '', 1)[::-1]
#         if 'AES' in ssid:
#             ssid = ssid.replace("AES", "CCMP")
#         try:
#             group_cipher = line.split('Group Cipher : ')[1].split('\n')[0]
#             pair_cipher = line.split('Pairwise Ciphers (1) : ')[1].split('\n')[0]
#         except:
#             group_cipher = ''
#             pair_cipher = ''
#     #    quality = line.split('Quality=')[1].split('Signal level')[0].replace(" ", "")
#         networks[ssid] = {'group_cipher': group_cipher, 'pair_cipher': pair_cipher}


app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def index():
    global command
    all_features = ['Current Weather','Daily Forecast','News', 'Sports (Upcoming Games)','Sports (Past Games)','Sports (Live Games)',
                    'Sports (Team Stats)','Custom Images', 'Custom GIFs', 'Custom Messages', 'Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Movies',
		    'IPO Calendar', 'Economic Calendar', 'Jokes', 'Gainers, Losers, Active', 'Sector Performance', 'Place (Reddit)', 'Clock 1']
    
    global professional
    
    try:
        f = open('csv/display_settings.json', 'r')
        feature_settings = json.load(f)
        feature_settings2 = feature_settings[0]
        f.close()
    except:
        feature_settings = ["Standard", [["Stocks", "Crypto", "Forex"]]]
        feature_settings2 = feature_settings[0]

    if not professional:
        try:
            f = open('csv/display_settings.json', 'r')
            currently_displaying = json.load(f)[1]
            f.close()
        except:
            currently_displaying = ["Standard", [["Stocks", "Crypto", "Forex"]]][1]
        not_displaying = [f for f in all_features if f not in currently_displaying[0]]
        not_displaying2 = [f for f in all_features if f not in currently_displaying[0]]

    elif professional:
        try:
            f = open('csv/display_settings.json', 'r')
            currently_displaying = json.load(f)[1]
            f.close()
        except:
            currently_displaying = ["Standard", [["Stocks", "Crypto", "Forex"]]][1]
        not_displaying = [f for f in all_features if f not in currently_displaying[0]]
        not_displaying2 = [f for f in all_features if f not in currently_displaying[1]]

    
#     with open('api_keys.txt', 'r') as f:
#         api_key2 = f.readlines()

    try:
        with open('movie_api_key.txt', 'r') as f:
            movie_api = f.readlines()
    except:
        movie_api = ''
    
    try:
        with open('ipo_api_key.txt', 'r') as f:
            ipo_api = f.readlines()
    except:
        ipo_api = ''    
    
    with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'r') as f:
        wifiline = f.readlines()

    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")
    logos_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logos')
    LogoList = os.listdir(logos_path)
	
    try:
        f = open('csv/stocks_settings.json', 'r')
        stocks_settings = json.load(f)
        f.close()
    except:
        stocks_settings = {"feature": "Stocks", "speed": "medium", "speed2": "medium", "animation": "down", "percent": False, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"AAPL": {"current": "164.02", "change": "-1.59", "percent_change": "-0.97"}, "MSFT": {"current": "288.29", "change": "-1.32", "percent_change": "-0.46"}, "GOOG": {"current": "2586.74", "change": "-34.01", "percent_change": "-1.31"}, "NFLX": {"current": "380.52", "change": "-7.59", "percent_change": "-1.99"}}, "prepost": False, "lohivol": False}
    
    dict1 = {
        "Aluminum": "ALU", "Brent Crude Oil": "BRENTOIL", "Coffee": "COFFEE", "Copper": "XCU", "Corn": "CORN", "Cotton": "COTTON", "Gold": "XAU",
        "Palladium": "XPD", "Platinum": "XPT", "Rice": "RICE", "Silver": "XAG", "Soybean": "SOYBEAN", "Sugar": "SUGAR", "Wheat": "WHEAT",
        "WTI Crude Oil": "WTIOIL", "Ethanol": "ETHANOL", "Crude Palm Oil": "CPO", "Natural Gas": "NG", "Cocoa": "COCOA", "Robusta": "ROBUSTA",
        "Lumber": "LUMBER", "Rubber": "RUBBER", "Live Cattle": "CATTLE", "Lean Hog": "HOG"}
    try:
        f = open('csv/commodities_settings.json', 'r')
        commodities_settings = json.load(f)
        f.close()
    except:
        commodities_settings = {"feature": "Stocks", "speed": "fast", "speed2": "fast", "animation": "down", "percent": True, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"BRENTOIL": {"current": "123.053", "unit": "bbl", "24hr_change": "1.0150", "percent_change": "0.83"}, "WTIOIL": {"current": "121.588", "unit": "bbl", "24hr_change": "0.8902", "percent_change": "0.74"}, "XAU": {"current": "1821.205", "unit": "oz", "24hr_change": "4.0045", "percent_change": "0.22"}, "XAG": {"current": "21.1034", "unit": "oz", "24hr_change": "-0.0550", "percent_change": "-0.26"}, "XCU": {"current": "0.2633", "unit": "oz", "24hr_change": "-0.0006", "percent_change": "-0.22"}, "NG": {"current": "8.6595", "unit": "mmbtu", "24hr_change": "-0.0236", "percent_change": "-0.27"}, "WHEAT": {"current": "393.123", "unit": "ton", "24hr_change": "-1.2642", "percent_change": "-0.32"}, "COTTON": {"current": "1.4494", "unit": "lb", "24hr_change": "0.0004", "percent_change": "0.03"}, "RICE": {"current": "16.3849", "unit": "cwt", "24hr_change": "0.0093", "percent_change": "0.06"}, "SUGAR": {"current": "0.1866", "unit": "lb", "24hr_change": "-0.0007", "percent_change": "-0.40"}, "COCOA": {"current": "2374.074", "unit": "ton", "24hr_change": "2.5206", "percent_change": "0.11"}, "LUMBER": {"current": "527.842", "unit": "oz", "24hr_change": "0.2641", "percent_change": "0.05"}, "SOYBEAN": {"current": "17.1621", "unit": "bu", "24hr_change": "0.0270", "percent_change": "0.16"}}}
    try:
        reversed_dict1 = {value: key for key, value in dict1.items()}
        commodities_settings['symbols'] = [reversed_dict1[value] for value in commodities_settings['symbols']]
    except:
        pass

    
    dict2 = {'BIST 100 - Istanbul': 'XU100.IS', 'SET - Bangkok': '^SET.BK', 'PSEI - Philippines': 'PSEI.PS', 'JKSE - Jakarta': '^JKSE',
        'TAIEX - Taiwan': '^TWII', 'HSI - Hong Kong': '^HSI', 'SENSEX - India': '^BSESN', 'NIFTY 50 - India': '^NSEI', 'Nikkei 225 - Japan': '^N225',
        'SZSE - Shenzhen': '399001.SZ', 'SSE - Shanghai': '000001.SS', 'STI - Singapore': '^STI', 'ASX 200 - Australia': '^AXJO',
        'NZX 50 - New Zealand': '^NZ50', 'KOSPI - South Korea': '^KS11','Euronext 100 - EU': '^N100', 'STOXX 50 - EU': '^STOXX50E',
        'STOXX 600 - EU': '^STOXX', 'PSI 20 - Lisbon': 'PSI20.LS', 'FTSE MIB - Italy': 'FTSEMIB.MI', 'OMXH25 - Helsinki': '^OMXH25',
        'OMXS30 - Stockholm': '^OMX', 'AEX - Amsterdam': '^AEX', 'ATX - Austria': '^ATX', 'BEL 20 - Brussels': '^BFX',
        'SSMI - Switzerland': '^SSMI', 'CAC 40 - France': '^FCHI', 'IBEX 35 - Spain': '^IBEX', 'FTSE 100 - UK': '^FTSE', 'Dax - Germany': '^GDAXI',
        'Bovespa - Brazil': '^BVSP', 'IPC - Mexico': '^MXX', 'S&P/TSX - Canada': '^GSPTSE', 'VIX - USA': '^VIX', 'Russell 2000 - USA': '^RUT',
        'Nasdaq Composite - USA': '^IXIC', 'Nasdaq 100 - USA': '^NDX', 'S&P 500 - USA': '^GSPC', 'Dow Jones - USA': '^DJI', 'U.S. Dollar (DXY) - USA': 'DX-Y.NYB',
	'E-Mini Dow Jones - USA': 'YM=F', 'E-Mini S&P 500 - USA': 'ES=F', 'E-Mini Nasdaq 100 - USA': 'NQ=F', 'E-Mini Russell 2000 - USA': 'RTY=F'}
    try:
        f = open('csv/indices_settings.json', 'r')
        indices_settings = json.load(f)
        f.close()
    except:
        indices_settings = {"feature": "Stocks", "speed": "fast", "speed2": "slow", "animation": "up", "percent": True, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"^HSI": {"name": "HSI", "current": "18083.06", "point_change": "1003.55", "percent_change": "5.88"}, "^GSPC": {"name": "S&P 500", "current": "3790.93", "point_change": "112.50", "percent_change": "3.06"}, "^RUT": {"name": "RUSSELL 2000", "current": "1775.77", "point_change": "66.90", "percent_change": "3.91"}, "^GDAXI": {"name": "DAX", "current": "12648.95", "point_change": "-21.53", "percent_change": "-0.17"}, "^FTSE": {"name": "FTSE 100", "current": "7058.68", "point_change": "-27.82", "percent_change": "-0.39"}, "^FCHI": {"name": "CAC 40", "current": "6031.45", "point_change": "-8.24", "percent_change": "-0.14"}, "399001.SZ": {"name": "SZSE", "current": "10778.61", "point_change": "-140.83", "percent_change": "-1.29"}, "^STOXX50E": {"name": "STOXX 50", "current": "3476.55", "point_change": "-7.93", "percent_change": "-0.23"}, "^AXJO": {"name": "ASX 200", "current": "6815.70", "point_change": "116.40", "percent_change": "1.74"}, "^DJI": {"name": "DOW JONES", "current": "30316.32", "point_change": "825.43", "percent_change": "2.80"}, "^STOXX": {"name": "STOXX 600", "current": "402.33", "point_change": "-0.70", "percent_change": "-0.17"}}}
    try:
        reversed_dict2 = {value: key for key, value in dict2.items()}
        indices_settings['symbols'] = [reversed_dict2[value] for value in indices_settings['symbols']]
    except:
        pass

    try:
        f= open('csv/crypto_settings.json', 'r')
        crypto_settings = json.load(f)
        f.close()
    except:
        crypto_settings = {"feature": "Stocks", "speed": "medium","speed2": "medium", "animation": "down", "percent": False, "point": True, "logos": True, "chart": False, "title": True, "lohivol": False, "symbols": {"ETH,USD": {"current": "2629.32", "24hr_change": "-27.6432", "percent_change": "-1.04"}, "BTC,USD": {"current": "38161.00", "24hr_change": "-50.8386", "percent_change": "-0.13"}, "BNB,USD": {"current": "372.57", "24hr_change": "0.4140", "percent_change": "0.11"}, "ADA,BTC": {"current": "0.0000", "24hr_change": "-0.0000", "percent_change": "-3.74"}}}
    
    try:
        f= open('csv/movie_settings.json', 'r')
        movie_settings = json.load(f)
        f.close()
    except:
        movie_settings = {"feature": "Movies", "speed": "fast", "speed2": "fast", "animation": "continuous", "category": "Popular All", "title": True, "movies": [{"title": "Avatar: The Way of Water", "language": "EN", "votes": "8.1", "date": "2022-12-14", "media_type": "Movie", "genre": ["Sci-Fi", "Action", "Adventure"], "backdrop": "198vrF8k7mfQ4FjDJsBmdQcaiyq.jpg", "logo": "https://image.tmdb.org/t/p/w500/198vrF8k7mfQ4FjDJsBmdQcaiyq.jpg"}, {"title": "Violent Night", "language": "EN", "votes": "7.3", "date": "2022-11-30", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime", "Thriller"], "backdrop": "g9Kb3RaLjsybI1jpqHQ3QZTCYpB.jpg", "logo": "https://image.tmdb.org/t/p/w500/g9Kb3RaLjsybI1jpqHQ3QZTCYpB.jpg"}, {"title": "Avatar", "language": "EN", "votes": "7.5", "date": "2009-12-15", "media_type": "Movie", "genre": ["Action", "Adventure", "Fantasy", "Sci-Fi"], "backdrop": "Yc9q6QuWrMp9nuDm5R8ExNqbEq.jpg", "logo": "https://image.tmdb.org/t/p/w500/Yc9q6QuWrMp9nuDm5R8ExNqbEq.jpg"}, {"title": "The Banshees of Inisherin", "language": "EN", "votes": "7.7", "date": "2022-10-21", "media_type": "Movie", "genre": ["Drama", "Comedy"], "backdrop": "9Md4CqzUGDtK5oEkRRvozLkGc9d.jpg", "logo": "https://image.tmdb.org/t/p/w500/9Md4CqzUGDtK5oEkRRvozLkGc9d.jpg"}, {"title": "Wednesday", "language": "EN", "votes": "8.8", "date": "2022-11-23", "media_type": "Tv", "genre": ["Sci-Fi & Fantasy", "Mystery", "Comedy"], "backdrop": "iHSwvRVsRyxpX7FE7GbviaDvgGZ.jpg", "logo": "https://image.tmdb.org/t/p/w500/iHSwvRVsRyxpX7FE7GbviaDvgGZ.jpg"}, {"title": "1923", "language": "EN", "votes": "8.8", "date": "2022-12-18", "media_type": "Tv", "genre": ["Drama", "Western"], "backdrop": "9I6LgZ5110ycg4pyobJxGTFWFCF.jpg", "logo": "https://image.tmdb.org/t/p/w500/9I6LgZ5110ycg4pyobJxGTFWFCF.jpg"}, {"title": "The Recruit", "language": "EN", "votes": "7.2", "date": "2022-12-16", "media_type": "Tv", "genre": ["Drama", "Crime"], "backdrop": "rey2eh6752C2UbGYRileKk1PVTo.jpg", "logo": "https://image.tmdb.org/t/p/w500/rey2eh6752C2UbGYRileKk1PVTo.jpg"}, {"title": "Black Adam", "language": "EN", "votes": "7.2", "date": "2022-10-19", "media_type": "Movie", "genre": ["Action", "Fantasy", "Sci-Fi"], "backdrop": "bQXAqRx2Fgc46uCVWgoPz5L5Dtr.jpg", "logo": "https://image.tmdb.org/t/p/w500/bQXAqRx2Fgc46uCVWgoPz5L5Dtr.jpg"}, {"title": "Nanny", "language": "EN", "votes": "5.4", "date": "2022-11-23", "media_type": "Movie", "genre": ["Horror", "Drama"], "backdrop": "nfuPlOK6ywGzKGb0yf7VJKyTFWb.jpg", "logo": "https://image.tmdb.org/t/p/w500/nfuPlOK6ywGzKGb0yf7VJKyTFWb.jpg"}, {"title": "Tom Clancys Jack Ryan", "language": "EN", "votes": "7.7", "date": "2018-08-30", "media_type": "Tv", "genre": ["Action & Adventure", "Drama", "War & Politics"], "backdrop": "6ovk8nrrSmN1ieT14zBAxcHbMU7.jpg", "logo": "https://image.tmdb.org/t/p/w500/6ovk8nrrSmN1ieT14zBAxcHbMU7.jpg"}, {"title": "High Heat", "language": "EN", "votes": "6.5", "date": "2022-12-16", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime"], "backdrop": "gjNM0odqkq5F7V58OjfTxPJ9p9Z.jpg", "logo": "https://image.tmdb.org/t/p/w500/gjNM0odqkq5F7V58OjfTxPJ9p9Z.jpg"}, {"title": "A Not So Merry Christmas", "language": "ES", "votes": "4.8", "date": "2022-12-20", "media_type": "Movie", "genre": ["Comedy"], "backdrop": "8uyJzaiGbiezZ9K48Cy5wXeqnYw.jpg", "logo": "https://image.tmdb.org/t/p/w500/8uyJzaiGbiezZ9K48Cy5wXeqnYw.jpg"}, {"title": "Guillermo del Toros Pinocchio", "language": "EN", "votes": "8.5", "date": "2022-11-09", "media_type": "Movie", "genre": ["Animation", "Fantasy", "Drama"], "backdrop": "e782pDRAlu4BG0ahd777n8zfPzZ.jpg", "logo": "https://image.tmdb.org/t/p/w500/e782pDRAlu4BG0ahd777n8zfPzZ.jpg"}, {"title": "His Dark Materials", "language": "EN", "votes": "8.0", "date": "2019-11-03", "media_type": "Tv", "genre": ["Sci-Fi & Fantasy", "Drama"], "backdrop": "dGOhplPZTL0SKyb0ocTFBHIuKUC.jpg", "logo": "https://image.tmdb.org/t/p/w500/dGOhplPZTL0SKyb0ocTFBHIuKUC.jpg"}, {"title": "The Fabelmans", "language": "EN", "votes": "7.8", "date": "2022-11-11", "media_type": "Movie", "genre": ["Drama", "Comedy"], "backdrop": "6RCf9jzKxyjblYV4CseayK6bcJo.jpg", "logo": "https://image.tmdb.org/t/p/w500/6RCf9jzKxyjblYV4CseayK6bcJo.jpg"}, {"title": "The Seven Deadly Sins: Grudge of Edinburgh Part 1", "language": "JA", "votes": "7.8", "date": "2022-12-20", "media_type": "Movie", "genre": ["Animation", "Fantasy", "Adventure", "Action"], "backdrop": "24fe6ou97ammOg3O6ShCgaiolp4.jpg", "logo": "https://image.tmdb.org/t/p/w500/24fe6ou97ammOg3O6ShCgaiolp4.jpg"}, {"title": "Mindcage", "language": "EN", "votes": "7.6", "date": "2022-12-16", "media_type": "Movie", "genre": ["Mystery", "Thriller", "Crime", "Drama"], "backdrop": "An2M2gm0p8POaiGTcZvP1JnUItH.jpg", "logo": "https://image.tmdb.org/t/p/w500/An2M2gm0p8POaiGTcZvP1JnUItH.jpg"}, {"title": "Private Lesson", "language": "TR", "votes": "7.3", "date": "2022-12-16", "media_type": "Movie", "genre": ["Comedy", "Romance"], "backdrop": "uZtYhcnk3WWvUzQkJLqnNywMQpb.jpg", "logo": "https://image.tmdb.org/t/p/w500/uZtYhcnk3WWvUzQkJLqnNywMQpb.jpg"}, {"title": "Sonic Prime", "language": "EN", "votes": "8.7", "date": "2022-12-15", "media_type": "Tv", "genre": ["Animation", "Family"], "backdrop": "1Iiz2uLcZuLn4Khog2yiKpbl11.jpg", "logo": "https://image.tmdb.org/t/p/w500/1Iiz2uLcZuLn4Khog2yiKpbl11.jpg"}, {"title": "The Big 4", "language": "ID", "votes": "7.0", "date": "2022-12-19", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime"], "backdrop": "clO1mWRYT24ogzN3o6LsqHjqrQu.jpg", "logo": "https://image.tmdb.org/t/p/w500/clO1mWRYT24ogzN3o6LsqHjqrQu.jpg"}]}

    try:
        f= open('csv/ipo_settings.json', 'r')
        ipo_settings = json.load(f)
        f.close()
    except:
        ipo_settings = {"feature": "IPO", "speed": "medium", "speed2": "medium", "animation": "down", "title": True, "symbols": ["No Data"]}
        with open('csv/ipo_settings.json', 'w') as f:
            json.dump(ipo_settings, f)
    try:
        f = open('csv/forex_settings.json', 'r')
        forex_settings = json.load(f)
        f.close()
    except:
        forex_settings = {"feature": "Stocks", "speed": "medium", "speed2": "medium", "animation": "down", "percent": False, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"EUR,USD": {"current": "1.1334", "24hr_change": "-0.0003", "percent_change": "0.00"}, "USD,JPY": {"current": "114.960", "24hr_change": "0.1600", "percent_change": "0.14"}, "GBP,USD": {"current": "1.3577", "24hr_change": "-0.0031", "percent_change": "-0.23"}, "USD,CHF": {"current": "0.9198", "24hr_change": "0.0029", "percent_change": "0.32"}}}

    try:    
        f = open('csv/current_weather.json', 'r')
        current_weather = json.load(f)
        f.close()
    except:
        current_weather = {"feature": "Current Weather", "speed": "medium", "animation": "down", "temp": "celsius", "wind_speed": "miles/hour", "colour": "white", "city_colour": "yellow", "title": True, "locations": {"Hong Kong": {"main_weather": "Clouds", "description": "overcast clouds", "temp": 30.4, "min_temp": 28.2, "max_temp": 30.8, "feels_like": 36.0, "humidity": 77, "clouds": 100, "visibility": 10000, "uv": 5.3, "rain_chance": 17, "wind_speed": 11.1, "wind_direction": 193, "is_day": 1}}, "current_weather": True, "speed2": "medium"}
    
    try:
        f = open('csv/daily_weather.json', 'r')
        daily_weather = json.load(f)
        f.close()
    except:
        daily_weather = {"feature": "Current Weather", "speed": "medium", "animation": "down", "temp": "celsius", "wind_speed": "miles/hour", "colour": "white", "city_colour": "yellow", "title": True, "locations": {"Hong Kong": [{"main_weather": "Thunderstorm", "description": "Slight or moderate", "min_temp": 28.2, "max_temp": 30.8, "temp": 30.4, "rain_chance": 17, "humidity": 77, "wind_speed": 11.1, "uv": 5.3, "clouds": 100, "wind_direction": 193, "visibility": 10000}, {"main_weather": "Clouds", "description": "overcast clouds", "min_temp": 27.9, "max_temp": 32.3}, {"main_weather": "Thunderstorm", "description": "Slight or moderate", "min_temp": 27.7, "max_temp": 31.2}, {"main_weather": "Thunderstorm", "description": "Slight or moderate", "min_temp": 28.1, "max_temp": 31.5}, {"main_weather": "Rain", "description": "light intensity shower rain", "min_temp": 28.5, "max_temp": 31.1}, {"main_weather": "Clouds", "description": "overcast clouds", "min_temp": 28.9, "max_temp": 31.5}, {"main_weather": "Clouds", "description": "scattered clouds", "min_temp": 29.0, "max_temp": 31.9}]}, "current_weather": False, "speed2": "medium"}
    
    try:
        f = open('csv/news_settings.json', 'r')
        news_settings = json.load(f)
        f.close()
    except:
        news_settings = {"feature": "News", "speed": "medium", "speed2": "medium", "animation": "down", "country": "US", "category": "General", "title": True, "headlines": [], "use_category": True, "use_country": False, "num_headlines": "10"}

    try:    
        f = open('csv/upcoming_games.json', 'r')
        upcoming_games = json.load(f)
        f.close()
    except:
        upcoming_games = {"feature": "Sports (Upcoming Games)", "speed": "medium", "speed2": "medium", "animation": "down", "title": True, "leagues": {"NFL": [{"date": "2021-11-22", "time": "01:20:00", "round": "11", "home_team": "Los Angeles Chargers", "home_score": "41", "away_team": "Pittsburgh Steelers", "away_score": "37"}]}}
    
    try:
        f = open('csv/live_games.json', 'r')
        live_games = json.load(f)
        f.close()
    except:
        live_games = {"feature": "Sports (Live Games)", "speed": "medium", "speed2": "medium", "animation": "down", "title": True, "leagues": {}}
    
    try:
        f = open('csv/past_games.json', 'r')
        past_games = json.load(f)
        f.close()
    except:
        past_games = {"feature": "Sports (Past Games)", "speed2": "medium", "speed": "medium", "animation": "down", "title": True, "leagues": {}}
    
    try:
        f = open('csv/league_tables.json', 'r')
        team_stats = json.load(f)
        f.close()
    except:
        team_stats = {"feature": "Sports (Team Stats)", "speed": "medium", "speed2": "medium","animation": "down", "title": True, "top20": 20, "leagues": {}}
    
    try:
        f = open('csv/image_settings.json', 'r')
        image_settings = json.load(f)
        f.close()
    except:
        image_settings = {"speed": "slow", "speed2": "medium","animation": "down", "title": True, "pause": "/", "images": []}
    
    try:
        f = open('csv/GIF_settings.json', 'r')
        GIF_settings = json.load(f)
        f.close()
    except:
        GIF_settings = {"speed": "medium", "speed2": "medium", "animation": "down", "title": True, "pause": "2", "images": []}
    
    try:
        f = open('csv/message_settings.json', 'r')
        message_settings = json.load(f)
        f.close()
    except:
        message_settings = {"feature": "Custom Messages", "speed": "medium", "speed2": "medium", "animation": "down", "title": False, "messages": [{"name": "welcome", "text": "Welcome to Fintic!", "text_colour": "White", "size": "Large", "background_colour": "Black"}, {"name": "get_started", "text": "To get started, connect your device to the \"Fintic Hotspot\" and access \"fintic.local:1024\" on your web browser. You can connect your ticker to Wi-Fi there.", "text_colour": "White", "size": "Small", "background_colour": "Black"}]}
    
    f = open('csv/general_settings.json', 'r')
    general_settings = json.load(f)
    f.close()

    try:
        f = open('csv/economic_settings.json', 'r')
        economic_settings = json.load(f)
        f.close()
    except:
        economic_settings = {"feature": "Economic Calendar", "speed": "medium", "speed2": "medium", "animation": "up", "importance": "Med - High", "title": True, "timezone": "US/Eastern", "countries": ["United States"], "events": []}
        with open('csv/economic_settings.json', 'w') as f:
            json.dump(economic_settings, f)
    try:
        f = open('csv/jokes_settings.json', 'r')
        jokes_settings = json.load(f)
        f.close()
        if not jokes_settings['categories']:
            jokes_settings['categories'] = ['Any']
    except:
        jokes_settings = {"feature": "Jokes", "speed": "medium", "speed2": "medium", "animation": "up", "title": True, "safe": True, "categories": ["Any"], "blacklist": [], "amount": "5", "jokes": []}
        with open('csv/jokes_settings.json', 'w') as f:
            json.dump(jokes_settings, f)
    try:
        f = open('csv/place_settings.json', 'r')
        place_settings = json.load(f)
        f.close()
    except:
        place_settings = {"feature": "Place", "speed": "medium", "speed2": "medium", "animation": "up", "title": True, "width": "128", "pause": "0", "places": ["r/place 2017", "r/place 2022"]}
        with open('csv/place_settings.json', 'w') as f:
            json.dump(place_settings, f)
    try:
        f = open('csv/market_settings.json', 'r')
        market_settings = json.load(f)
        f.close()
    except:
        market_settings = {"feature": "Gainers, Losers, Active", "speed": "medium", "speed2": "medium", "animation": "up", "percent": True, "point": True, "logos": True, "chart": False, "title": True, "lohivol": False, "categories": ["Top Gainers", "Top Losers", "Most Active"], "gainers": {}, "losers": {}, "mostactive": {}}
        with open('csv/market_settings.json', 'w') as f:
            json.dump(market_settings, f)
    try:
        f = open('csv/sector_settings.json', 'r')
        sector_settings = json.load(f)
        f.close()
    except:
        sector_settings = {"feature": "Sector Performance", "speed": "medium", "speed2": "medium", "animation": "up", "logos": True, "title": True, "sectors": ["Energy", "Financials", "Real Estate", "Technology"], "data": {}}
        with open('csv/sector_settings.json', 'w') as f:
            json.dump(sector_settings, f)
    try:
        f = open('clock_screensaver.json', 'r')
        clock_screensaver = json.load(f)
        f.close()
    except:
        clock_screensaver = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}
        with open('clock_screensaver.json', 'w') as f:
            json.dump(clock_screensaver, f)
    try:
        f = open('csv/clock1_settings.json', 'r')
        clock1_settings = json.load(f)
        f.close()        
    except:
        clock1_settings = {"speed": "fast", "speed2": "fast", "transition": "up", "pause": "20"}
        with open('csv/clock1_settings.json', 'w') as f:
            json.dump(clock1_settings, f)
    try:
        f = open('csv/clock2_settings.json', 'r')
        clock2_settings = json.load(f)
        f.close()        
    except:
        clock2_settings = {"speed": "fast", "speed2": "fast", "transition": "up", "pause": "20"}
        with open('csv/clock2_settings.json', 'w') as f:
            json.dump(clock2_settings, f)
    try:
        f = open('csv/worldclock_settings.json', 'r')
        worldclock_settings = json.load(f)
        f.close()        
    except:
        worldclock_settings = {"speed": "fast", "speed2": "fast", "transition": "up", "pause": "20"}
        with open('csv/worldclock_settings.json', 'w') as f:
            json.dump(worldclock_settings, f)
    try:
        f = open('csv/scheduler.json','r')
        scheduler_settings = json.load(f)
        if 'screensaver' not in str(scheduler_settings):
            scheduler_settings['screensaver1'] = {}
            scheduler_settings['screensaver1']['hour'] = '00'
            scheduler_settings['screensaver1']['minute'] = '00'
            scheduler_settings['screensaver1']['endhour'] = '00'
            scheduler_settings['screensaver1']['endminute'] = '00'
            scheduler_settings['screensaver1']['type'] = 'World Clock'
            scheduler_settings['screensaver1']['enabled'] = False
            scheduler_settings['screensaver2'] = {}
            scheduler_settings['screensaver2']['hour'] = '00'
            scheduler_settings['screensaver2']['minute'] = '00'
            scheduler_settings['screensaver2']['endhour'] = '00'
            scheduler_settings['screensaver2']['endminute'] = '00'
            scheduler_settings['screensaver2']['type'] = 'Clock 2'
            scheduler_settings['screensaver2']['enabled'] = False
            scheduler_settings['screensaver3'] = {}
            scheduler_settings['screensaver3']['hour'] = '00'
            scheduler_settings['screensaver3']['minute'] = '00'
            scheduler_settings['screensaver3']['endhour'] = '00'
            scheduler_settings['screensaver3']['endminute'] = '00'
            scheduler_settings['screensaver3']['type'] = 'Clock 1'
            scheduler_settings['screensaver3']['enabled'] = False
        f.close()
    except:
        scheduler_settings = {"shutdown": {"hour": "00", "minute": "00", "enabled": False}, "reboot":{"hour": "00", "minute": "00", "enabled": False}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "screensaver1":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"World Clock", "enabled": False}, "screensaver2":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 1", "enabled": False}, "screensaver3":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 2", "enabled": False}}

#     try: # incase this doesnt exist
#         api_keys = api_key2[1]
#     except:
#         api_keys = ''
    
    try:
        movie_api_key = movie_api[0]
    except:
        movie_api_key = ''

    try:
        ipo_api_key = ipo_api[0]
    except:
        ipo_api_key = ''
    try:
        wifi_SSID = wifiline[5][6:].replace('"','')
    except:
        wifi_SSID = ''
    try:
        networks_list = networks
    except:
        networks_list = ''

    templateData = {
        'system_info':system_info,
        'currently_displaying': currently_displaying,
        'feature_settings2': feature_settings2,
        'not_displaying': not_displaying, 
        'not_displaying2': not_displaying2, 
        'stocks_settings': stocks_settings, 
        'commodities_settings': commodities_settings,
        'indices_settings': indices_settings,
        'crypto_settings': crypto_settings,
        'forex_settings': forex_settings,
        'current_weather': current_weather,
        'daily_weather': daily_weather,
        'movie_settings': movie_settings,
        'ipo_settings': ipo_settings,
        'news_settings': news_settings,
        'upcoming_games': upcoming_games,
        'past_games': past_games,
        'live_games': live_games,
        'team_stats': team_stats,
        'image_settings':image_settings,
        'GIF_settings':GIF_settings, 
        'message_settings':message_settings,
        'professional':professional,
        'general_settings':general_settings,
        'movie_api_key':movie_api_key,
        'ipo_api_key':ipo_api_key,
        'wifi_SSID':wifi_SSID,
        'scheduler_settings':scheduler_settings,
        'economic_settings':economic_settings,
        'jokes_settings':jokes_settings,
        'place_settings':place_settings,
        'market_settings':market_settings,
        'sector_settings':sector_settings,
        'networks_list': networks_list,
        'clock_screensaver': clock_screensaver,
        'clock1_settings': clock1_settings,
        'clock2_settings': clock2_settings,
        'worldclock_settings': worldclock_settings
      }
      

    return render_template('index.html', **templateData)



def scheduled_brightness():
    try:
        while True:
            try:
                f = open('csv/scheduler.json','r')
                schedules = json.load(f)
                f.close()
            except:
                schedules = {"shutdown": {"hour": "00", "minute": "00", "enabled": False}, "reboot":{"hour": "00", "minute": "00", "enabled": False}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "screensaver1":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"World Clock", "enabled": False}, "screensaver2":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 1", "enabled": False}, "screensaver3":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 2", "enabled": False}}

            timezone_brightness = schedules['timezone']

            brightness1_hour = schedules['brightness1']['hour']
            brightness1_minute = schedules['brightness1']['minute']
            brightness1_bright = schedules['brightness1']['bright']
            brightness1_enabled = schedules['brightness1']['enabled']

            brightness2_hour = schedules['brightness2']['hour']
            brightness2_minute = schedules['brightness2']['minute']
            brightness2_bright = schedules['brightness2']['bright']
            brightness2_enabled = schedules['brightness2']['enabled']

            brightness3_hour = schedules['brightness3']['hour']
            brightness3_minute = schedules['brightness3']['minute']
            brightness3_bright = schedules['brightness3']['bright']
            brightness3_enabled = schedules['brightness3']['enabled']

            brightness4_hour = schedules['brightness4']['hour']
            brightness4_minute = schedules['brightness4']['minute']
            brightness4_bright = schedules['brightness4']['bright']
            brightness4_enabled = schedules['brightness4']['enabled']

            try:
                if brightness1_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness1_hour+':'+brightness1_minute:
                    brightness = max(min(int(brightness1_bright), 10), 1)
                    ticker.sendline(str(brightness-1))
                    f = open('csv/general_settings.json', 'r')
                    general_settings = json.load(f)
                    f.close()
                    general_settings['brightness'] = int(brightness)
                    f = open('csv/general_settings.json', 'w')
                    json.dump(general_settings, f)
                    f.close()
            except:
                pass
            try:
                if brightness2_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness2_hour+':'+brightness2_minute:
                    brightness = max(min(int(brightness2_bright), 10), 1)
                    ticker.sendline(str(brightness-1))
                    f = open('csv/general_settings.json', 'r')
                    general_settings = json.load(f)
                    f.close()
                    general_settings['brightness'] = int(brightness)
                    f = open('csv/general_settings.json', 'w')
                    json.dump(general_settings, f)
                    f.close()
            except:
                pass
            try:
                if brightness3_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness3_hour+':'+brightness3_minute:
                    brightness = max(min(int(brightness3_bright), 10), 1)
                    ticker.sendline(str(brightness-1))
                    f = open('csv/general_settings.json', 'r')
                    general_settings = json.load(f)
                    f.close()
                    general_settings['brightness'] = int(brightness)
                    f = open('csv/general_settings.json', 'w')
                    json.dump(general_settings, f)
                    f.close()
            except:
                pass
            try:
                if brightness4_enabled and datetime.datetime.now(pytz.timezone(timezone_brightness)).strftime("%H:%M") == brightness4_hour+':'+brightness4_minute:
                    brightness = max(min(int(brightness4_bright), 10), 1)
                    ticker.sendline(str(brightness-1))
                    f = open('csv/general_settings.json', 'r')
                    general_settings = json.load(f)
                    f.close()
                    general_settings['brightness'] = int(brightness)
                    f = open('csv/general_settings.json', 'w')
                    json.dump(general_settings, f)
                    f.close()
            except:
                pass
            time.sleep(20)
    except:
        pass

scheduled_b = Process(target=scheduled_brightness)
scheduled_b.start()


def scheduled_screensaver():

    already_running_screensaver_1 = False
    already_running_screensaver_2 = False
    already_running_screensaver_3 = False
    try:
        while True:
            try:
                f = open('csv/scheduler.json','r')
                schedules = json.load(f)
                f.close()
            except:
                schedules = {"shutdown": {"hour": "00", "minute": "00", "enabled": False}, "reboot":{"hour": "00", "minute": "00", "enabled": False}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "screensaver1":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"World Clock", "enabled": False}, "screensaver2":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 1", "enabled": False}, "screensaver3":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 2", "enabled": False}}

            timezone_screensaver = schedules['timezone']

            try:
                screensaver1_hour = schedules['screensaver1']['hour']
                screensaver1_minute = schedules['screensaver1']['minute']
                screensaver1_enabled = schedules['screensaver1']['enabled']
                screensaver1_type = [schedules['screensaver1']['type']]
                screensaver1_endhour = schedules['screensaver1']['endhour']
                screensaver1_endminute = schedules['screensaver1']['endminute']
            except:
                screensaver1_hour = '00'
                screensaver1_minute = '00'
                screensaver1_enabled = False
                screensaver1_type = ['World Clock']
                screensaver1_endhour = '00'
                screensaver1_endminute = '00'

            try:
                screensaver2_hour = schedules['screensaver2']['hour']
                screensaver2_minute = schedules['screensaver2']['minute']
                screensaver2_enabled = schedules['screensaver2']['enabled']
                screensaver2_type = [schedules['screensaver2']['type']]
                screensaver2_endhour = schedules['screensaver2']['endhour']
                screensaver2_endminute = schedules['screensaver2']['endminute']
            except:
                screensaver2_hour = '00'
                screensaver2_minute = '00'
                screensaver2_enabled = False
                screensaver2_type = ['Clock 1']
                screensaver2_endhour = '00'
                screensaver2_endminute = '00'

            try:
                screensaver3_hour = schedules['screensaver3']['hour']
                screensaver3_minute = schedules['screensaver3']['minute']
                screensaver3_enabled = schedules['screensaver3']['enabled']
                screensaver3_type = [schedules['screensaver3']['type']]
                screensaver3_endhour = schedules['screensaver3']['endhour']
                screensaver3_endminute = schedules['screensaver3']['endminute']
            except:
                screensaver3_hour = '00'
                screensaver3_minute = '00'
                screensaver3_enabled = False
                screensaver3_type = ['Clock 2']
                screensaver3_endhour = '00'
                screensaver3_endminute = '00'

            time_now = datetime.datetime.now(pytz.timezone(timezone_screensaver)).strftime("%H:%M")

            try:
                if screensaver1_enabled and time_now == screensaver1_hour+':'+screensaver1_minute and not already_running_screensaver_1:
                    requests.post('http://fintic.local:1024/screensaver', json=screensaver1_type)
                    already_running_screensaver_1  = True
            except:
                pass
            try:
                if screensaver1_enabled and time_now == screensaver1_endhour+':'+screensaver1_endminute and already_running_screensaver_1:
                    already_running_screensaver_1  = False
                    if ((time_now == screensaver2_hour+':'+screensaver2_minute and screensaver2_enabled) or (time_now == screensaver3_hour+':'+screensaver3_minute and screensaver3_enabled)):
                        pass
                    else:
                        requests.put('http://fintic.local:1024/start')
            except:
                pass
            try:
                if screensaver2_enabled and time_now == screensaver2_hour+':'+screensaver2_minute and not already_running_screensaver_2:
                    requests.post('http://fintic.local:1024/screensaver', json=screensaver2_type)
                    already_running_screensaver_2  = True
            except:
                pass
            try:
                if screensaver2_enabled and time_now == screensaver2_endhour+':'+screensaver2_endminute and already_running_screensaver_2:
                    already_running_screensaver_2  = False
                    if (time_now == screensaver1_hour+':'+screensaver1_minute and screensaver1_enabled) or (time_now == screensaver3_hour+':'+screensaver3_minute and screensaver3_enabled):
                        pass
                    else:
                        requests.put('http://fintic.local:1024/start')
            except:
                pass
            try:
                if screensaver3_enabled and time_now == screensaver3_hour+':'+screensaver3_minute and not already_running_screensaver_3:
                    requests.post('http://fintic.local:1024/screensaver', json=screensaver3_type)
                    already_running_screensaver_3  = True
            except:
                pass
            try:
                if screensaver3_enabled and time_now == screensaver3_endhour+':'+screensaver3_endminute and already_running_screensaver_3:
                    already_running_screensaver_3  = False
                    if (time_now == screensaver1_hour+':'+screensaver1_minute and screensaver1_enabled) or (time_now == screensaver2_hour+':'+screensaver2_minute and screensaver2_enabled):
                        pass
                    else:
                        requests.put('http://fintic.local:1024/start')
            except:
                pass

            time.sleep(20)
    except:
        pass

scheduled_s = Process(target=scheduled_screensaver)
scheduled_s.start()


def save_displaying(input_settings):
    
    global professional
  
    all_settings = ['Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Current Weather', 'Daily Forecast', 'News', 'Sports (Upcoming Games)', 'Sports (Past Games)',
                    'Sports (Live Games)', 'Sports (Team Stats)', 'Custom Images', 'Custom GIFs', 'Custom Messages', 'Movies', 'IPO Calendar', 'Economic Calendar', 'Jokes', 'Gainers, Losers, Active', 'Sector Performance', 'Place (Reddit)', 'Clock 1']
    professional = len(input_settings) == 2
    if professional:
        all_settings = ['Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices', 'Current Weather', 'News', 'Daily Forecast', 'Sports (Upcoming Games)',
                        'Sports (Past Games)', 'Sports (Team Stats)', 'Sports (Live Games)', 'Custom Messages', 'Custom Images', 'Movies', 'IPO Calendar', 'Economic Calendar', 'Jokes', 'Gainers, Losers, Active', 'Sector Performance', 'Place (Reddit)', 'Clock 1']
        
    positions = []
    display_settings = []

    if professional:
        input_settings[0] = [i for i in input_settings[0] if i in all_settings]
        input_settings[1] = [i for i in input_settings[1] if i in all_settings]
   
    s = "Professional" if professional else "Standard"
    display_settings = [s] + [input_settings]
    with open('csv/display_settings.json', 'w') as f:
        json.dump(list(display_settings), f)
        
        
        
@app.route ("/start", methods = ['PUT', 'POST'])
def start():
     
    global displaying_screensaver
    global ticker
    #global api_caller
    global professional
    global ticker_stopped
    if displaying_screensaver:
        screensaver_p.close()
        ticker = pexpect.spawn("sudo -E python3 -W ignore stockTicker.py")
        #api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 api_caller.py")
        #api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 database_caller.py")
        displaying_screensaver = False
        
    if ticker_stopped:
        ticker = pexpect.spawn("sudo -E python3 -W ignore stockTicker.py")
        ticker_stopped = False
        
    #api_caller.sendline('A')

    global scheduled_b
    if scheduled_b.is_alive():
        scheduled_b.terminate()
    scheduled_b = Process(target=scheduled_brightness)
    scheduled_b.start()

    global scheduled_s
    if scheduled_s.is_alive():
        scheduled_s.terminate()
    scheduled_s = Process(target=scheduled_screensaver)
    scheduled_s.start()
	
    ticker.sendline('K')

    ticker.sendline('A')
    return index()
    
@app.route("/stop")
def stop():

    global displaying_screensaver
    global ticker
    #global api_caller
    global professional
    global ticker_stopped
    
    
    
    if not displaying_screensaver:
        ticker.sendline('K')
        time.sleep(0.1) # give time for leds to turn off
        ticker.close()
    else:
        screensaver_p.close()
        
    if not ticker_stopped:
        
        time.sleep(0.1) # give time for leds to turn off
        ticker.close()
        ticker_stopped = True
        
     
    if displaying_screensaver:
        screensaver_p.close()
        #ticker = pexpect.spawn("sudo -E python3 -W ignore stockTicker.py")
        #api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 api_caller.py")
        #api_caller = pexpect.spawn("sudo -E taskset -c 3 python3 database_caller.py")
        displaying_screensaver = False


    scheduled_b.terminate()
    scheduled_s.terminate()

    return index()

@app.route("/update", methods=['PUT','POST'])
def update():

    
    
    try:
        f = open('csv/system_info.json', 'r')
        system_info = json.load(f)
    except Exception as e:
        system_info = {"update_available": False, "first_boot": False}
      
    system_info['update_available'] = False
    f = open('csv/system_info.json', 'w')
    json.dump(system_info, f)
    f.close()
    

    os.system("./update.sh")
    os.system("sudo reboot now")
    return index()

@app.route("/restart")
def restart():
    os.system("sudo reboot now")
    return index()
    
@app.route("/reset")
def reset():
   
    os.system("sudo ./setup_config_files.sh")
    time.sleep(2)
    os.system("sudo reboot now")
    return index()
    
@app.route("/save", methods = ['PUT', 'POST', 'GET'])
def save():
   
    global uploading
    
    data = str(request.data.decode('utf-8'))

    input_settings = json.loads(data)
  
    save_displaying(input_settings['displaying'])
    
    input_settings= input_settings['feature_settings']
    
    feature = input_settings['feature'] 
    if feature in ['Stocks', 'Crypto', 'Forex', 'Commodities', 'Indices']:
        save_trade_settings(input_settings)
    elif feature in ['Current Weather', 'Daily Forecast']:
        save_weather_settings(input_settings)
    elif feature == 'News':
        save_news_settings(input_settings)
    elif feature == 'Movies':
        save_movie_settings(input_settings)
    elif feature == 'IPO Calendar':
        save_ipo_settings(input_settings)
    elif feature == 'Economic Calendar':
        save_economic_settings(input_settings)
    elif feature == 'Jokes':
        save_jokes_settings(input_settings)
    elif 'Sports' in feature:
        save_sports_settings(input_settings)
    elif feature == 'Gainers, Losers, Active':
        save_market_settings(input_settings)
    elif feature == 'Sector Performance':
        save_sector_settings(input_settings)
    elif feature == 'Place (Reddit)':
        save_place_settings(input_settings)
    elif feature in ['Custom GIFs', 'Custom Images']:

        images = request.files
        names = list(request.files.keys())

        for name in names:

            images[name].save('user_uploads/' +name)
     
        save_image_settings(input_settings)
        
    elif feature == 'Custom Messages':
        save_message_settings(input_settings)
        
    return index()


# saves files uploaded to the webpage for images and GIFs
@app.route("/upload", methods = ['PUT', 'POST', 'GET'])
def upload():
 
    global uploading
    uploading = True
    try:
        
        images = request.files
        names = list(request.files.keys())

        for name in names:
            images[name].save('user_uploads/' +name)
 
    except Exception as e:

         uploading = False
    return index()

def remove_old_uploads():
    #remove old files 
    
    
    
    f = open('csv/image_settings.json', 'r')
    image_settings = json.load(f)
    f.close()
    f = open('csv/GIF_settings.json', 'r')
    GIF_settings = json.load(f)
    f.close()
    for filename in os.listdir('user_uploads'):
        if filename not in image_settings['images'] and filename not in GIF_settings['images']:
            os.remove('user_uploads/'+filename)



@app.route("/brightness", methods=['PUT','POST'])
def brightness():
    global brightness
    data= request.data.decode('utf-8')
    settings = json.loads(data)

    brightness =settings['brightness']
    brightness = max(min(int(brightness), 10), 1)
    ticker.sendline(str(brightness-1))
    f = open('csv/general_settings.json', 'r')
    general_settings = json.load(f)
    f.close()
    general_settings['brightness'] = int(brightness)
    f = open('csv/general_settings.json', 'w')
    json.dump(general_settings, f)
    f.close()
    return index()


def edit_wpa_sup(country, ssid, pwd):
    current_wpa = open('/etc/wpa_supplicant/wpa_supplicant.conf')

    wpa_lines = current_wpa.readlines()

    wpa_lines[2] = 'country={}\n'.format(country)

    current_wpa.close()

    #remove this line to append to end instead of overwriting all networks 
    wpa_lines = wpa_lines[0:3]

    
    # create new file from scratch
    wpa_lines = []
    wpa_lines.append('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
    wpa_lines.append('update_config=1\n')
    wpa_lines.append('country={}\n'.format(country))

    
    wpa_lines.append('\n')
    wpa_lines.append('network={\n')
    wpa_lines.append('\tssid="{}"\n'.format(ssid))
    wpa_lines.append('\tpsk="{}"\n'.format(pwd))
    wpa_lines.append('}\n')

    wpa_string = ''.join(wpa_lines)
  
    current_wpa = open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w')
    current_wpa.write(wpa_string)
    
    
@app.route("/wifi", methods = ['PUT', 'POST', 'GET'])
def set_wifi():

    data= request.data.decode('utf-8')
    
    settings = json.loads(data)
    
    country = settings['country'].upper()
    ssid = settings['ssid']
    pwd = settings['pwd']
    
    f = open('csv/general_settings.json', 'r')
    general_settings = json.load(f)
    f.close()
    general_settings['country_code'] = country
    f = open('csv/general_settings.json', 'w')
    json.dump(general_settings, f)
    f.close()
    
    edit_wpa_sup(country, ssid, pwd)
    # resstart netoworking
    os.system('wpa_cli -i wlan0 reconfigure')
    return index()

#def check_internet_connection(host='http://google.com'):
    
    #try:
        #urllib.request.urlopen(host) #Python 3.x
        #return True
    #except:
        #return False
        
#def check_network_connection():
    #ps = subprocess.Popen(['iwconfig'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    #try:
        #output = subprocess.check_output(('grep', 'ESSID'), stdin=ps.stdout)
        #return True
    #except subprocess.CalledProcessError:
        # grep did not match any lines
        
        #return False
    
def edit_hosts(hostname):
    current_hosts = open('/etc/hosts')

    hosts_lines = current_hosts.readlines()


    hosts_lines[5] = '127.0.1.1       {}'.format(hostname)

    current_hosts.close()
    
    hosts_string = ''.join(hosts_lines)
    
    current_hosts = open('/etc/hosts', 'w+')
    current_hosts.write(hosts_string)
    
@app.route("/hostname", methods = ['PUT', 'POST', 'GET'])
def hostname():
    data= request.data.decode('utf-8')
    settings = json.loads(data)
    hostname = settings['hostname']

    
    edit_hosts(hostname)
    os.system("sudo hostnamectl set-hostname {}".format(hostname))
    os.system("sudo systemctl restart avahi-daemon")
    
    f = open('csv/general_settings.json', 'r')
    general_settings = json.load(f)
    f.close()
    
    general_settings['hostname'] = hostname
    f = open('csv/general_settings.json', 'w')
    json.dump(general_settings, f)
    f.close()
    
    return index()


# @app.route("/saveWeatherAPIKey", methods = ['PUT', 'POST'])
# def saveWeatherAPIKey():
    
#     data= request.data.decode('utf-8')
#     settings = json.loads(data)
    
#     key = settings['api_key']

#     with open('./api_keys.txt') as f:
#         lines = f.readlines()
#         if len(lines) == 1:
#             lines.append(str(key))
#         elif len(lines) == 2:
#             lines[1] = str(key)

#     with open('./api_keys.txt', 'w') as f:
#         for line in lines:
#             f.write(line)
#     return index()
    
 
    
@app.route("/saveMovieAPIKey", methods = ['PUT', 'POST'])
def saveMovieAPIKey():
    
    data= request.data.decode('utf-8')
    settings = json.loads(data)
    
    key = settings['api_key']

    with open('movie_api_key.txt', 'w') as f:
        f.write(str(key))

    return index()
    
@app.route("/saveIpoAPIKey", methods = ['PUT', 'POST'])
def saveIpoAPIKey():
    
    data= request.data.decode('utf-8')
    settings = json.loads(data)
    
    key = settings['api_key']

    with open('ipo_api_key.txt', 'w') as f:
        f.write(str(key))

    return index()

@app.route("/savePortfolioSettings", methods = ['PUT', 'POST'])
def savePortfolioSettings():
	
    data= request.data.decode('utf-8')
    settings = json.loads(data)
 
    #THIS IS TO CREATE PORTFOLIO JSON FILE IF IT DOESN'T EXIST
    initialize_json = '{"symbols":{}}'
    if 'portfolio_settings.json' not in os.listdir('csv/'):
        with open('csv/portfolio_settings.json', 'w') as f:
            f.write(initialize_json)
	
    try:
        f = open('csv/portfolio_settings.json')
        portfolio = json.load(f)
        f.close()

        shares1 = settings['shares']
        cost1 = settings['cost']
        symbol1 = settings['symbol']
	
        days1 = settings['days']
        # day_start = datetime.datetime.strptime(str(days1), "%Y-%m-%d")
        # day_today = datetime.datetime.strptime(datetime.datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d")
        # days1 = str((day_today - day_start).days)

        portfolio['symbols'][symbol1] = {'shares':shares1, 'day':days1, 'cost':cost1}

        f = open("csv/portfolio_settings.json", 'w+')
        json.dump(portfolio, f)
        f.close()
    except:
        pass

    return index()

@app.route("/savePortfolioCryptoSettings", methods = ['PUT', 'POST'])
def savePortfolioCryptoSettings():
	
    data= request.data.decode('utf-8')
    settings = json.loads(data)
 
    #THIS IS TO CREATE PORTFOLIO JSON FILE IF IT DOESN'T EXIST
    initialize_json = '{"symbols":{}}'
    if 'portfolio_crypto_settings.json' not in os.listdir('csv/'):
        with open('csv/portfolio_crypto_settings.json', 'w') as f:
            f.write(initialize_json)
	
    try:
        f = open('csv/portfolio_crypto_settings.json')
        portfolio = json.load(f)
        f.close()

        shares1 = settings['shares']
        cost1 = settings['cost']
        symbol1 = settings['symbol']
	
        days1 = settings['days']
        # day_start = datetime.datetime.strptime(str(days1), "%Y-%m-%d")
        # day_today = datetime.datetime.strptime(datetime.datetime.now(pytz.utc).strftime("%Y-%m-%d"), "%Y-%m-%d")
        # days1 = str((day_today - day_start).days)

        portfolio['symbols'][symbol1] = {'shares':shares1, 'day':days1, 'cost':cost1}

        f = open("csv/portfolio_crypto_settings.json", 'w+')
        json.dump(portfolio, f)
        f.close()
    except:
        pass

    return index()


@app.route("/deletePortfolioSettings", methods = ['PUT', 'POST'])
def deletePortfolioSettings():

    data= request.data.decode('utf-8')
    settings = json.loads(data)

    try:
        g = open('csv/portfolio_settings.json')
        portfolio = json.load(g)
        g.close()
	
        symbol = settings
        # DELETE SYMBOLS FUNCTION
        try:
            portfolio['symbols'].pop(symbol)
        except:
            pass

        f = open("csv/portfolio_settings.json", 'w+')
        json.dump(portfolio, f)
        f.close()
    except:
        pass

    return index()

@app.route("/deletePortfolioCryptoSettings", methods = ['PUT', 'POST'])
def deletePortfolioCryptoSettings():

    data= request.data.decode('utf-8')
    settings = json.loads(data)

    try:
        g = open('csv/portfolio_crypto_settings.json')
        portfolio = json.load(g)
        g.close()
	
        symbol = settings
        # DELETE SYMBOLS FUNCTION
        try:
            portfolio['symbols'].pop(symbol)
        except:
            pass

        f = open("csv/portfolio_crypto_settings.json", 'w+')
        json.dump(portfolio, f)
        f.close()
    except:
        pass

    return index()


@app.route("/screensaver", methods = ['PUT', 'POST'])
def screensaver():
    global displaying_screensaver
    global ticker
    #global api_caller
    global screensaver_p
    
    data = str(request.data)
    
    if displaying_screensaver:
        screensaver_p.close()
    else:
        #api_caller.close()
        ticker.close()

    
    if "Pulsating Colors" in data:
        screensaver_p = pexpect.spawn("sudo -E python3 pulsing-colors.py --led-gpio-mapping=adafruit-hat --led-slowdown-gpio=4 -r 32 --led-cols 64 -c 2 -P 1")
    elif "Rotating Square" in data:
        screensaver_p = pexpect.spawn("sudo ./demo --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=128 -D 0")
    elif "Pulsating brightness" in data:
        screensaver_p = pexpect.spawn("sudo -E python3 pulsing-brightness.py --led-gpio-mapping=adafruit-hat --led-slowdown-gpio=4 -r 32 --led-cols 64 -c 2 -P 1")
    elif "Volume Bars" in data:
        screensaver_p = pexpect.spawn("sudo ./demo --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=128 -D 9")
    elif "Evolution of Color" in data:
        screensaver_p = pexpect.spawn("sudo ./demo --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=128 -D 10 -m 100")
    elif "Conway" in data:
        screensaver_p = pexpect.spawn("sudo ./demo --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=128 -D 7 -m 100")
    elif "Abelian Sandpile Model" in data:
        screensaver_p = pexpect.spawn("sudo ./demo --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=128 -D 6")
    elif "Grayscale Block" in data:
        screensaver_p = pexpect.spawn("sudo ./demo --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=128 -D 5")
    elif "Clock 1" in data:
        screensaver_p = pexpect.spawn("sudo python3 clock_screensaver.py")
    elif "Clock 2" in data:
        screensaver_p = pexpect.spawn("sudo python3 clock_screensaver2.py")
    elif "World Clock" in data:
        screensaver_p = pexpect.spawn("sudo python3 world_clock2.py")
    elif "Sleep" in data:
        screensaver_p = DummyProcess()
    else: #default in case user hasnt set one yet
        screensaver_p = DummyProcess()
        
    scheduled_b.terminate()        
    displaying_screensaver = True
    return index()
        
        
            

def combine_dict(current_settings, input_symbols, current_key):
    # removes keys not in input from current_settings[current_key] and adds keys not in current from input 
    new_settings = copy.deepcopy(current_settings)
    new_settings[current_key] = {}
    
    current_symbols = list(current_settings[current_key].keys())
    
    # add any stock that arent current in the settings
    for IS in input_symbols:
        if IS not in current_symbols:
            new_settings[current_key][IS] = []
        else:
            new_settings[current_key][IS] = current_settings[current_key][IS]
    
            
    return new_settings
    
def save_trade_settings(input_settings):

    commodities_dict = {
        "Aluminum": "ALU", "Brent Crude Oil": "BRENTOIL", "Coffee": "COFFEE", "Copper": "XCU", "Corn": "CORN", "Cotton": "COTTON", "Gold": "XAU",
        "Palladium": "XPD", "Platinum": "XPT", "Rice": "RICE", "Silver": "XAG", "Soybean": "SOYBEAN", "Sugar": "SUGAR", "Wheat": "WHEAT",
        "WTI Crude Oil": "WTIOIL", "Ethanol": "ETHANOL", "Crude Palm Oil": "CPO", "Natural Gas": "NG", "Cocoa": "COCOA", "Robusta": "ROBUSTA",
        "Lumber": "LUMBER", "Rubber": "RUBBER", "Live Cattle": "CATTLE", "Lean Hog": "HOG" 
    }
    indices_dict = {'BIST 100 - Istanbul': 'XU100.IS', 'SET - Bangkok': '^SET.BK', 'PSEI - Philippines': 'PSEI.PS', 'JKSE - Jakarta': '^JKSE',
        'TAIEX - Taiwan': '^TWII', 'HSI - Hong Kong': '^HSI', 'SENSEX - India': '^BSESN', 'NIFTY 50 - India': '^NSEI', 'Nikkei 225 - Japan': '^N225',
        'SZSE - Shenzhen': '399001.SZ', 'SSE - Shanghai': '000001.SS', 'STI - Singapore': '^STI', 'ASX 200 - Australia': '^AXJO',
        'NZX 50 - New Zealand': '^NZ50', 'KOSPI - South Korea': '^KS11','Euronext 100 - EU': '^N100', 'STOXX 50 - EU': '^STOXX50E',
        'STOXX 600 - EU': '^STOXX', 'PSI 20 - Lisbon': 'PSI20.LS', 'FTSE MIB - Italy': 'FTSEMIB.MI', 'OMXH25 - Helsinki': '^OMXH25',
        'OMXS30 - Stockholm': '^OMX', 'AEX - Amsterdam': '^AEX', 'ATX - Austria': '^ATX', 'BEL 20 - Brussels': '^BFX',
        'SSMI - Switzerland': '^SSMI', 'CAC 40 - France': '^FCHI', 'IBEX 35 - Spain': '^IBEX', 'FTSE 100 - UK': '^FTSE', 'Dax - Germany': '^GDAXI',
        'Bovespa - Brazil': '^BVSP', 'IPC - Mexico': '^MXX', 'S&P/TSX - Canada': '^GSPTSE', 'VIX - USA': '^VIX', 'Russell 2000 - USA': '^RUT',
        'Nasdaq Composite - USA': '^IXIC', 'Nasdaq 100 - USA': '^NDX', 'S&P 500 - USA': '^GSPC', 'Dow Jones - USA': '^DJI', 'U.S. Dollar (DXY) - USA': 'DX-Y.NYB',
        'E-Mini Dow Jones - USA': 'YM=F', 'E-Mini S&P 500 - USA': 'ES=F', 'E-Mini Nasdaq 100 - USA': 'NQ=F', 'E-Mini Russell 2000 - USA': 'RTY=F'}
	
    try:
        filename = input_settings['feature'].lower() + '_settings.json'
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        if input_settings['feature'].lower() == 'stocks':
            current_settings = {"feature": "Stocks", "speed": "medium", "speed2": "medium", "animation": "down", "percent": False, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"AAPL": {"current": "164.02", "change": "-1.59", "percent_change": "-0.97"}, "MSFT": {"current": "288.29", "change": "-1.32", "percent_change": "-0.46"}, "GOOG": {"current": "2586.74", "change": "-34.01", "percent_change": "-1.31"}, "NFLX": {"current": "380.52", "change": "-7.59", "percent_change": "-1.99"}}, "prepost": False, "lohivol": False}
        elif input_settings['feature'].lower() == 'crypto':
            current_settings = {"feature": "Stocks", "speed": "medium","speed2": "medium", "animation": "down", "percent": False, "point": True, "logos": True, "chart": False, "title": True, "lohivol": False, "symbols": {"ETH,USD": {"current": "2629.32", "24hr_change": "-27.6432", "percent_change": "-1.04"}, "BTC,USD": {"current": "38161.00", "24hr_change": "-50.8386", "percent_change": "-0.13"}, "BNB,USD": {"current": "372.57", "24hr_change": "0.4140", "percent_change": "0.11"}, "ADA,BTC": {"current": "0.0000", "24hr_change": "-0.0000", "percent_change": "-3.74"}}}
        elif input_settings['feature'].lower() == 'indices':
            current_settings = {"feature": "Stocks", "speed": "fast", "speed2": "slow", "animation": "up", "percent": True, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"^HSI": {"name": "HSI", "current": "18083.06", "point_change": "1003.55", "percent_change": "5.88"}, "^GSPC": {"name": "S&P 500", "current": "3790.93", "point_change": "112.50", "percent_change": "3.06"}, "^RUT": {"name": "RUSSELL 2000", "current": "1775.77", "point_change": "66.90", "percent_change": "3.91"}, "^GDAXI": {"name": "DAX", "current": "12648.95", "point_change": "-21.53", "percent_change": "-0.17"}, "^FTSE": {"name": "FTSE 100", "current": "7058.68", "point_change": "-27.82", "percent_change": "-0.39"}, "^FCHI": {"name": "CAC 40", "current": "6031.45", "point_change": "-8.24", "percent_change": "-0.14"}, "399001.SZ": {"name": "SZSE", "current": "10778.61", "point_change": "-140.83", "percent_change": "-1.29"}, "^STOXX50E": {"name": "STOXX 50", "current": "3476.55", "point_change": "-7.93", "percent_change": "-0.23"}, "^AXJO": {"name": "ASX 200", "current": "6815.70", "point_change": "116.40", "percent_change": "1.74"}, "^DJI": {"name": "DOW JONES", "current": "30316.32", "point_change": "825.43", "percent_change": "2.80"}, "^STOXX": {"name": "STOXX 600", "current": "402.33", "point_change": "-0.70", "percent_change": "-0.17"}}}
        elif input_settings['feature'].lower() == 'commodities':
            current_settings = {"feature": "Stocks", "speed": "fast", "speed2": "fast", "animation": "down", "percent": True, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"BRENTOIL": {"current": "123.053", "unit": "bbl", "24hr_change": "1.0150", "percent_change": "0.83"}, "WTIOIL": {"current": "121.588", "unit": "bbl", "24hr_change": "0.8902", "percent_change": "0.74"}, "XAU": {"current": "1821.205", "unit": "oz", "24hr_change": "4.0045", "percent_change": "0.22"}, "XAG": {"current": "21.1034", "unit": "oz", "24hr_change": "-0.0550", "percent_change": "-0.26"}, "XCU": {"current": "0.2633", "unit": "oz", "24hr_change": "-0.0006", "percent_change": "-0.22"}, "NG": {"current": "8.6595", "unit": "mmbtu", "24hr_change": "-0.0236", "percent_change": "-0.27"}, "WHEAT": {"current": "393.123", "unit": "ton", "24hr_change": "-1.2642", "percent_change": "-0.32"}, "COTTON": {"current": "1.4494", "unit": "lb", "24hr_change": "0.0004", "percent_change": "0.03"}, "RICE": {"current": "16.3849", "unit": "cwt", "24hr_change": "0.0093", "percent_change": "0.06"}, "SUGAR": {"current": "0.1866", "unit": "lb", "24hr_change": "-0.0007", "percent_change": "-0.40"}, "COCOA": {"current": "2374.074", "unit": "ton", "24hr_change": "2.5206", "percent_change": "0.11"}, "LUMBER": {"current": "527.842", "unit": "oz", "24hr_change": "0.2641", "percent_change": "0.05"}, "SOYBEAN": {"current": "17.1621", "unit": "bu", "24hr_change": "0.0270", "percent_change": "0.16"}}}
        elif input_settings['feature'].lower() == 'forex':
            current_settings = {"feature": "Stocks", "speed": "medium", "speed2": "medium", "animation": "down", "percent": False, "point": True, "logos": True, "chart": False, "title": True, "symbols": {"EUR,USD": {"current": "1.1334", "24hr_change": "-0.0003", "percent_change": "0.00"}, "USD,JPY": {"current": "114.960", "24hr_change": "0.1600", "percent_change": "0.14"}, "GBP,USD": {"current": "1.3577", "24hr_change": "-0.0031", "percent_change": "-0.23"}, "USD,CHF": {"current": "0.9198", "24hr_change": "0.0029", "percent_change": "0.32"}}}

    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['percent'] = input_settings['percent']
    current_settings['point'] = input_settings['point']
    current_settings['logos'] = input_settings['logos']
    current_settings['title'] = input_settings['title']
    if input_settings['feature'] == 'Stocks':
        current_settings['prepost'] = input_settings['prepost']
    if input_settings['feature'] == 'Stocks' or input_settings['feature'] == 'Crypto':
        current_settings['chart'] = input_settings['chart']
        current_settings['lohivol'] = input_settings['lohivol']
    if input_settings['feature'] == 'Commodities':
        try:
            input_settings['symbols'] = [commodities_dict[symbol] for symbol in input_settings['symbols']]
        except:
            pass
    if input_settings['feature'] == 'Indices':
        try:
            input_settings['symbols'] = [indices_dict[symbol] for symbol in input_settings['symbols']]
        except:
            pass
    
    current_settings = combine_dict(current_settings, input_settings['symbols'], 'symbols')
    
    with open('csv/' + filename, 'w') as f:
        json.dump(current_settings,f)

    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()
    
    if any([current_settings['symbols'][k] == [] for k in input_settings['symbols']]):
        last_updates[input_settings['feature'].lower()]['force'] = True
        if input_settings['feature'] == 'Stocks':
            last_updates['prepost']['force'] = True

    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()
        
    
def save_weather_settings(input_settings):
    
    filename = 'current_weather.json' if input_settings['feature'] == 'Current Weather' else 'daily_weather.json'

    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        if input_settings['feature'] == 'Current Weather':
            current_settings = {"feature": "Current Weather", "speed": "medium", "animation": "down", "temp": "celsius", "wind_speed": "miles/hour", "colour": "white", "city_colour": "yellow", "title": True, "locations": {"Hong Kong": {"main_weather": "Clouds", "description": "overcast clouds", "temp": 30.4, "min_temp": 28.2, "max_temp": 30.8, "feels_like": 36.0, "humidity": 77, "clouds": 100, "visibility": 10000, "uv": 5.3, "rain_chance": 17, "wind_speed": 11.1, "wind_direction": 193, "is_day": 1}}, "current_weather": True, "speed2": "medium"}
        else:
            current_settings = {"feature": "Current Weather", "speed": "medium", "animation": "down", "temp": "celsius", "wind_speed": "miles/hour", "colour": "white", "city_colour": "yellow", "title": True, "locations": {"Hong Kong": [{"main_weather": "Thunderstorm", "description": "Slight or moderate", "min_temp": 28.2, "max_temp": 30.8, "temp": 30.4, "rain_chance": 17, "humidity": 77, "wind_speed": 11.1, "uv": 5.3, "clouds": 100, "wind_direction": 193, "visibility": 10000}, {"main_weather": "Clouds", "description": "overcast clouds", "min_temp": 27.9, "max_temp": 32.3}, {"main_weather": "Thunderstorm", "description": "Slight or moderate", "min_temp": 27.7, "max_temp": 31.2}, {"main_weather": "Thunderstorm", "description": "Slight or moderate", "min_temp": 28.1, "max_temp": 31.5}, {"main_weather": "Rain", "description": "light intensity shower rain", "min_temp": 28.5, "max_temp": 31.1}, {"main_weather": "Clouds", "description": "overcast clouds", "min_temp": 28.9, "max_temp": 31.5}, {"main_weather": "Clouds", "description": "scattered clouds", "min_temp": 29.0, "max_temp": 31.9}]}, "current_weather": False, "speed2": "medium"}
    
    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['temp'] = input_settings['temp'].lower()
    current_settings['wind_speed'] = input_settings['wind_speed'].lower()
    current_settings['title'] = input_settings['title']
    
    if input_settings['feature'] == 'Daily Forecast':
        current_settings['current_weather'] = input_settings['current_weather']

    current_settings = combine_dict(current_settings, input_settings['locations'], 'locations')
    
    with open('csv/' + filename, 'w+') as f:
        json.dump(current_settings,f)

    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()
    if any([current_settings['locations'][k] == [] for k in input_settings['locations']]):
        last_updates['weather']['force'] = True
        
    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()
    

def save_news_settings(input_settings):

    filename = 'news_settings.json' 
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "News", "speed": "medium", "speed2": "medium", "animation": "down", "country": "US", "category": "General", "title": True, "headlines": [], "use_category": True, "use_country": False, "num_headlines": "10"}
    
    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['category'] = input_settings['category']
    current_settings['country'] = input_settings['country']
    current_settings['use_category'] = input_settings['use_category']
    current_settings['use_country'] = input_settings['use_country']
    current_settings['num_headlines'] = input_settings['num_headlines']
    
    with open('csv/' + filename, 'w') as f:
        json.dump(current_settings,f)

    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()
    
    last_updates['news']['force'] = True
        
    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()
    
    
def save_movie_settings(input_settings):
    filename = 'movie_settings.json' 
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "Movies", "speed": "fast", "speed2": "fast", "animation": "continuous", "category": "Popular All", "title": True, "movies": [{"title": "Avatar: The Way of Water", "language": "EN", "votes": "8.1", "date": "2022-12-14", "media_type": "Movie", "genre": ["Sci-Fi", "Action", "Adventure"], "backdrop": "198vrF8k7mfQ4FjDJsBmdQcaiyq.jpg", "logo": "https://image.tmdb.org/t/p/w500/198vrF8k7mfQ4FjDJsBmdQcaiyq.jpg"}, {"title": "Violent Night", "language": "EN", "votes": "7.3", "date": "2022-11-30", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime", "Thriller"], "backdrop": "g9Kb3RaLjsybI1jpqHQ3QZTCYpB.jpg", "logo": "https://image.tmdb.org/t/p/w500/g9Kb3RaLjsybI1jpqHQ3QZTCYpB.jpg"}, {"title": "Avatar", "language": "EN", "votes": "7.5", "date": "2009-12-15", "media_type": "Movie", "genre": ["Action", "Adventure", "Fantasy", "Sci-Fi"], "backdrop": "Yc9q6QuWrMp9nuDm5R8ExNqbEq.jpg", "logo": "https://image.tmdb.org/t/p/w500/Yc9q6QuWrMp9nuDm5R8ExNqbEq.jpg"}, {"title": "The Banshees of Inisherin", "language": "EN", "votes": "7.7", "date": "2022-10-21", "media_type": "Movie", "genre": ["Drama", "Comedy"], "backdrop": "9Md4CqzUGDtK5oEkRRvozLkGc9d.jpg", "logo": "https://image.tmdb.org/t/p/w500/9Md4CqzUGDtK5oEkRRvozLkGc9d.jpg"}, {"title": "Wednesday", "language": "EN", "votes": "8.8", "date": "2022-11-23", "media_type": "Tv", "genre": ["Sci-Fi & Fantasy", "Mystery", "Comedy"], "backdrop": "iHSwvRVsRyxpX7FE7GbviaDvgGZ.jpg", "logo": "https://image.tmdb.org/t/p/w500/iHSwvRVsRyxpX7FE7GbviaDvgGZ.jpg"}, {"title": "1923", "language": "EN", "votes": "8.8", "date": "2022-12-18", "media_type": "Tv", "genre": ["Drama", "Western"], "backdrop": "9I6LgZ5110ycg4pyobJxGTFWFCF.jpg", "logo": "https://image.tmdb.org/t/p/w500/9I6LgZ5110ycg4pyobJxGTFWFCF.jpg"}, {"title": "The Recruit", "language": "EN", "votes": "7.2", "date": "2022-12-16", "media_type": "Tv", "genre": ["Drama", "Crime"], "backdrop": "rey2eh6752C2UbGYRileKk1PVTo.jpg", "logo": "https://image.tmdb.org/t/p/w500/rey2eh6752C2UbGYRileKk1PVTo.jpg"}, {"title": "Black Adam", "language": "EN", "votes": "7.2", "date": "2022-10-19", "media_type": "Movie", "genre": ["Action", "Fantasy", "Sci-Fi"], "backdrop": "bQXAqRx2Fgc46uCVWgoPz5L5Dtr.jpg", "logo": "https://image.tmdb.org/t/p/w500/bQXAqRx2Fgc46uCVWgoPz5L5Dtr.jpg"}, {"title": "Nanny", "language": "EN", "votes": "5.4", "date": "2022-11-23", "media_type": "Movie", "genre": ["Horror", "Drama"], "backdrop": "nfuPlOK6ywGzKGb0yf7VJKyTFWb.jpg", "logo": "https://image.tmdb.org/t/p/w500/nfuPlOK6ywGzKGb0yf7VJKyTFWb.jpg"}, {"title": "Tom Clancys Jack Ryan", "language": "EN", "votes": "7.7", "date": "2018-08-30", "media_type": "Tv", "genre": ["Action & Adventure", "Drama", "War & Politics"], "backdrop": "6ovk8nrrSmN1ieT14zBAxcHbMU7.jpg", "logo": "https://image.tmdb.org/t/p/w500/6ovk8nrrSmN1ieT14zBAxcHbMU7.jpg"}, {"title": "High Heat", "language": "EN", "votes": "6.5", "date": "2022-12-16", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime"], "backdrop": "gjNM0odqkq5F7V58OjfTxPJ9p9Z.jpg", "logo": "https://image.tmdb.org/t/p/w500/gjNM0odqkq5F7V58OjfTxPJ9p9Z.jpg"}, {"title": "A Not So Merry Christmas", "language": "ES", "votes": "4.8", "date": "2022-12-20", "media_type": "Movie", "genre": ["Comedy"], "backdrop": "8uyJzaiGbiezZ9K48Cy5wXeqnYw.jpg", "logo": "https://image.tmdb.org/t/p/w500/8uyJzaiGbiezZ9K48Cy5wXeqnYw.jpg"}, {"title": "Guillermo del Toros Pinocchio", "language": "EN", "votes": "8.5", "date": "2022-11-09", "media_type": "Movie", "genre": ["Animation", "Fantasy", "Drama"], "backdrop": "e782pDRAlu4BG0ahd777n8zfPzZ.jpg", "logo": "https://image.tmdb.org/t/p/w500/e782pDRAlu4BG0ahd777n8zfPzZ.jpg"}, {"title": "His Dark Materials", "language": "EN", "votes": "8.0", "date": "2019-11-03", "media_type": "Tv", "genre": ["Sci-Fi & Fantasy", "Drama"], "backdrop": "dGOhplPZTL0SKyb0ocTFBHIuKUC.jpg", "logo": "https://image.tmdb.org/t/p/w500/dGOhplPZTL0SKyb0ocTFBHIuKUC.jpg"}, {"title": "The Fabelmans", "language": "EN", "votes": "7.8", "date": "2022-11-11", "media_type": "Movie", "genre": ["Drama", "Comedy"], "backdrop": "6RCf9jzKxyjblYV4CseayK6bcJo.jpg", "logo": "https://image.tmdb.org/t/p/w500/6RCf9jzKxyjblYV4CseayK6bcJo.jpg"}, {"title": "The Seven Deadly Sins: Grudge of Edinburgh Part 1", "language": "JA", "votes": "7.8", "date": "2022-12-20", "media_type": "Movie", "genre": ["Animation", "Fantasy", "Adventure", "Action"], "backdrop": "24fe6ou97ammOg3O6ShCgaiolp4.jpg", "logo": "https://image.tmdb.org/t/p/w500/24fe6ou97ammOg3O6ShCgaiolp4.jpg"}, {"title": "Mindcage", "language": "EN", "votes": "7.6", "date": "2022-12-16", "media_type": "Movie", "genre": ["Mystery", "Thriller", "Crime", "Drama"], "backdrop": "An2M2gm0p8POaiGTcZvP1JnUItH.jpg", "logo": "https://image.tmdb.org/t/p/w500/An2M2gm0p8POaiGTcZvP1JnUItH.jpg"}, {"title": "Private Lesson", "language": "TR", "votes": "7.3", "date": "2022-12-16", "media_type": "Movie", "genre": ["Comedy", "Romance"], "backdrop": "uZtYhcnk3WWvUzQkJLqnNywMQpb.jpg", "logo": "https://image.tmdb.org/t/p/w500/uZtYhcnk3WWvUzQkJLqnNywMQpb.jpg"}, {"title": "Sonic Prime", "language": "EN", "votes": "8.7", "date": "2022-12-15", "media_type": "Tv", "genre": ["Animation", "Family"], "backdrop": "1Iiz2uLcZuLn4Khog2yiKpbl11.jpg", "logo": "https://image.tmdb.org/t/p/w500/1Iiz2uLcZuLn4Khog2yiKpbl11.jpg"}, {"title": "The Big 4", "language": "ID", "votes": "7.0", "date": "2022-12-19", "media_type": "Movie", "genre": ["Action", "Comedy", "Crime"], "backdrop": "clO1mWRYT24ogzN3o6LsqHjqrQu.jpg", "logo": "https://image.tmdb.org/t/p/w500/clO1mWRYT24ogzN3o6LsqHjqrQu.jpg"}]}
    
    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['category'] = input_settings['category']
 
    with open('csv/' + filename, 'w') as f:
        json.dump(current_settings, f)

    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()
    
    last_updates['movies']['force'] = True
        
    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()


def save_ipo_settings(input_settings):
    filename = 'ipo_settings.json' 
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "IPO", "speed": "medium", "speed2": "medium", "animation": "down", "title": True, "symbols": ["No Data"]}
    
    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']

    with open('csv/' + filename, 'w') as f:
        json.dump(current_settings,f)

    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()
    
    last_updates['ipo']['force'] = True
        
    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()


def save_economic_settings(input_settings):
    filename = 'economic_settings.json'
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "Economic Calendar", "speed": "medium", "speed2": "medium", "animation": "up", "importance": "Med - High", "title": True, "timezone": "US/Eastern", "countries": ["United States"], "events": []}
	
    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['timezone'] = input_settings['timezone']
    current_settings['countries'] = input_settings['countries']
    current_settings['importance'] = input_settings['importance']

    try:
        f = open('csv/' + filename, 'w')
        json.dump(current_settings, f)
        f.close()
    except:
        with open('csv/economic_settings.json', 'w') as f:
            json.dump(current_settings, f)
	
    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()

    last_updates['economic']['force'] = True

    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()


def save_jokes_settings(input_settings):
    filename = 'jokes_settings.json'
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "Jokes", "speed": "medium", "speed2": "medium", "animation": "up", "title": True, "safe": True, "categories": ["Any"], "blacklist": [], "amount": "5", "jokes": []}

    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['safe'] = input_settings['safe']
    if not input_settings['categories']:
        current_settings['categories'] = ['Any']
    else:
        current_settings['categories'] = input_settings['categories']
    current_settings['blacklist'] = input_settings['blacklist']
    current_settings['amount'] = input_settings['amount']

    try:
        f = open('csv/' + filename, 'w')
        json.dump(current_settings, f)
        f.close()
    except:
        with open('csv/jokes_settings.json', 'w') as f:
            json.dump(current_settings, f)
    
    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()
    last_updates['jokes']['force'] = True
    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()


def save_market_settings(input_settings):
    filename = 'market_settings.json'
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "Gainers, Losers, Active", "speed": "medium", "speed2": "medium", "animation": "up", "percent": True, "point": True, "logos": True, "chart": False, "title": True, "lohivol": False, "categories": ["Top Gainers", "Top Losers", "Most Active"], "gainers": {}, "losers": {}, "mostactive": {}}

    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['logos'] = input_settings['logos']
    current_settings['percent'] = input_settings['percent']
    current_settings['point'] = input_settings['point']
    current_settings['categories'] = input_settings['categories']
    current_settings['lohivol'] = input_settings['lohivol']
    try:
        f = open('csv/' + filename, 'w')
        json.dump(current_settings, f)
        f.close()
    except:
        with open('csv/market_settings.json', 'w') as f:
            json.dump(current_settings, f)
        
    # f = open('csv/last_updates.json', 'r')
    # last_updates = json.load(f)
    # f.close()

    # last_updates['market']['force'] = True

    # f = open('csv/last_updates.json', 'w')
    # json.dump(last_updates, f)
    # f.close()


def save_sector_settings(input_settings):
    filename = 'sector_settings.json'
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "Sector Performance", "speed": "medium", "speed2": "medium", "animation": "up", "logos": True, "title": True, "sectors": ["Energy", "Financials", "Real Estate", "Technology"], "data": {}}

    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['logos'] = input_settings['logos']
    current_settings['sectors'] = input_settings['categories']
    try:
        f = open('csv/' + filename, 'w')
        json.dump(current_settings, f)
        f.close()
    except:
        with open('csv/sector_settings.json', 'w') as f:
            json.dump(current_settings, f)
        
    # f = open('csv/last_updates.json', 'r')
    # last_updates = json.load(f)
    # f.close()

    # last_updates['sector']['force'] = True

    # f = open('csv/last_updates.json', 'w')
    # json.dump(last_updates, f)
    # f.close()


def save_place_settings(input_settings):
    filename = 'place_settings.json'
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "Place", "speed": "medium", "speed2": "medium", "animation": "up", "title": True, "width": "128", "pause": "0", "places": ["r/place 2017", "r/place 2022"]}

    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['width'] = input_settings['width']
    current_settings['pause'] = input_settings['pause']
    current_settings['places'] = input_settings['places']
    try:
        f = open('csv/' + filename, 'w')
        json.dump(current_settings, f)
        f.close()
    except:
        with open('csv/place_settings.json', 'w') as f:
            json.dump(current_settings, f)



def save_sports_settings(input_settings):
    
    feature = input_settings['feature']
    
    if feature == 'Sports (Upcoming Games)':
        filename = 'upcoming_games.json'
        update_key = 'sports_u'
    elif feature == 'Sports (Past Games)':
        filename = 'past_games.json'
        update_key = 'sports_p'
    elif feature == 'Sports (Live Games)':
        filename = 'live_games.json'
        update_key = 'sports_l'
    elif feature == 'Sports (Team Stats)':
        filename = 'league_tables.json'
        update_key = 'sports_t'
    
    try:
        f = open('csv/' + filename, 'r')
        current_settings = json.load(f)
        f.close()
    except:
        if feature == 'Sports (Upcoming Games)':
            current_settings = {"feature": "Sports (Upcoming Games)", "speed": "medium", "speed2": "medium", "animation": "down", "title": True, "leagues": {"NFL": [{"date": "2021-11-22", "time": "01:20:00", "round": "11", "home_team": "Los Angeles Chargers", "home_score": "41", "away_team": "Pittsburgh Steelers", "away_score": "37"}]}}
        elif feature == 'Sports (Past Games)':
            current_settings = {"feature": "Sports (Past Games)", "speed2": "medium", "speed": "medium", "animation": "down", "title": True, "leagues": {}}
        elif feature == 'Sports (Live Games)':
            current_settings = {"feature": "Sports (Live Games)", "speed": "medium", "speed2": "medium", "animation": "down", "title": True, "leagues": {}}
        elif feature == 'Sports (Team Stats)':
            current_settings = {"feature": "Sports (Team Stats)", "speed": "medium", "speed2": "medium","animation": "down", "title": True, "top20": 20, "leagues": {}}
    
    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    current_settings['title'] = input_settings['title']
    current_settings['feature'] = input_settings['feature']
    
    current_settings = combine_dict(current_settings, input_settings['leagues'], 'leagues')
    
    with open('csv/' + filename, 'w') as f:
        json.dump(current_settings,f)

    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()
    
    if any([current_settings['leagues'][k] == [] for k in input_settings['leagues']]):
        last_updates[update_key]['force'] = True
        
    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()
    

# for images and GIFs
def save_image_settings(input_settings):
    filename = 'image_settings.json' if input_settings['feature'] == 'Custom Images' else 'GIF_settings.json' 
    
    current_settings = input_settings
    
    current_settings['speed'] = input_settings['speed'].lower()
    current_settings['speed2'] = input_settings['speed2'].lower()
    current_settings['animation'] = input_settings['animation'].lower()
    
    del current_settings['feature']

    with open('csv/' + filename, 'w') as f:
        json.dump(current_settings,f)

    remove_old_uploads()


def save_message_settings(input_settings):
    try:
        f = open('csv/message_settings.json', 'r')
        current_settings = json.load(f)
        f.close()
    except:
        current_settings = {"feature": "Custom Messages", "speed": "medium", "speed2": "medium", "animation": "down", "title": False, "messages": [{"name": "welcome", "text": "Welcome to Fintic!", "text_colour": "White", "size": "Large", "background_colour": "Black"}, {"name": "get_started", "text": "To get started, connect your device to the \"Fintic Hotspot\" and access \"fintic.local:1024\" on your web browser. You can connect your ticker to Wi-Fi there.", "text_colour": "White", "size": "Small", "background_colour": "Black"}]}

    new_settings = copy.deepcopy(input_settings)

    for i,IS in enumerate(input_settings['messages']):
        # check if this is in current_settings
        for CS in current_settings['messages']:
            if IS['name'] == CS['name']:
                new_settings['messages'][i] = CS
                break

    with open('csv/message_settings.json', 'w') as f:
        json.dump(new_settings,f)


@app.route("/shutdown")
def shutdown():
    os.system("sudo shutdown now")
    return index()
    
	
@app.route("/saveSchedulerSettings", methods = ['PUT', 'POST'])
def saveSchedulerSettings():
    
    data= request.data.decode('utf-8')
    input_settings = json.loads(data)
    
    initialize_json = '{"shutdown": {"hour": "00", "minute": "00", "enabled": false}, "reboot":{"hour": "00", "minute": "00", "enabled": false}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": false}, "screensaver1":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"World Clock", "enabled": false}, "screensaver2":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 1", "enabled": false}, "screensaver3":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 2", "enabled": false}}'

    if 'scheduler.json' not in os.listdir('csv/'):
        with open('csv/scheduler.json', 'w') as f:
            f.write(initialize_json)

    try:
        with open('csv/scheduler.json','r') as f:
            scheduler_settings = json.load(f)
        if 'screensaver' not in str(scheduler_settings):
            scheduler_settings['screensaver1'] = {}
            scheduler_settings['screensaver1']['hour'] = '00'
            scheduler_settings['screensaver1']['minute'] = '00'
            scheduler_settings['screensaver1']['endhour'] = '00'
            scheduler_settings['screensaver1']['endminute'] = '00'
            scheduler_settings['screensaver1']['type'] = 'World Clock'
            scheduler_settings['screensaver1']['enabled'] = False
            scheduler_settings['screensaver2'] = {}
            scheduler_settings['screensaver2']['hour'] = '00'
            scheduler_settings['screensaver2']['minute'] = '00'
            scheduler_settings['screensaver2']['endhour'] = '00'
            scheduler_settings['screensaver2']['endminute'] = '00'
            scheduler_settings['screensaver2']['type'] = 'Clock 2'
            scheduler_settings['screensaver2']['enabled'] = False
            scheduler_settings['screensaver3'] = {}
            scheduler_settings['screensaver3']['hour'] = '00'
            scheduler_settings['screensaver3']['minute'] = '00'
            scheduler_settings['screensaver3']['endhour'] = '00'
            scheduler_settings['screensaver3']['endminute'] = '00'
            scheduler_settings['screensaver3']['type'] = 'Clock 1'
            scheduler_settings['screensaver3']['enabled'] = False
    except:
        scheduler_settings = {"shutdown": {"hour": "00", "minute": "00", "enabled": False}, "reboot":{"hour": "00", "minute": "00", "enabled": False}, "timezone": "GMT", "brightness1":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness2":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness3":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "brightness4":{"hour": "00", "minute": "00", "bright": "10", "enabled": False}, "screensaver1":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"World Clock", "enabled": False}, "screensaver2":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 1", "enabled": False}, "screensaver3":{"hour": "00", "minute": "00", "endhour": "00", "endminute": "00", "type":"Clock 2", "enabled": False}}

    scheduler_settings['shutdown']['hour'] = input_settings['shutdown_hour']
    scheduler_settings['shutdown']['minute'] = input_settings['shutdown_minute']
    scheduler_settings['shutdown']['enabled'] = input_settings['shutdown_enabled']

    scheduler_settings['reboot']['hour'] = input_settings['reboot_hour']
    scheduler_settings['reboot']['minute'] = input_settings['reboot_minute']
    scheduler_settings['reboot']['enabled'] = input_settings['reboot_enabled']    

    scheduler_settings['brightness1']['hour'] = input_settings['brightness1_hour']
    scheduler_settings['brightness1']['minute'] = input_settings['brightness1_minute']
    scheduler_settings['brightness1']['enabled'] = input_settings['brightness1_enabled']
    scheduler_settings['brightness1']['bright'] = input_settings['brightness1_bright']

    scheduler_settings['brightness2']['hour'] = input_settings['brightness2_hour']
    scheduler_settings['brightness2']['minute'] = input_settings['brightness2_minute']
    scheduler_settings['brightness2']['enabled'] = input_settings['brightness2_enabled']
    scheduler_settings['brightness2']['bright'] = input_settings['brightness2_bright']
	
    scheduler_settings['brightness3']['hour'] = input_settings['brightness3_hour']
    scheduler_settings['brightness3']['minute'] = input_settings['brightness3_minute']
    scheduler_settings['brightness3']['enabled'] = input_settings['brightness3_enabled']
    scheduler_settings['brightness3']['bright'] = input_settings['brightness3_bright']

    scheduler_settings['brightness4']['hour'] = input_settings['brightness4_hour']
    scheduler_settings['brightness4']['minute'] = input_settings['brightness4_minute']
    scheduler_settings['brightness4']['enabled'] = input_settings['brightness4_enabled']
    scheduler_settings['brightness4']['bright'] = input_settings['brightness4_bright']

    scheduler_settings['screensaver1']['hour'] = input_settings['screensaver1_hour']
    scheduler_settings['screensaver1']['minute'] = input_settings['screensaver1_minute']
    scheduler_settings['screensaver1']['endhour'] = input_settings['screensaver1_endhour']
    scheduler_settings['screensaver1']['endminute'] = input_settings['screensaver1_endminute']
    scheduler_settings['screensaver1']['type'] = input_settings['screensaver1_type']
    scheduler_settings['screensaver1']['enabled'] = input_settings['screensaver1_enabled']

    scheduler_settings['screensaver2']['hour'] = input_settings['screensaver2_hour']
    scheduler_settings['screensaver2']['minute'] = input_settings['screensaver2_minute']
    scheduler_settings['screensaver2']['endhour'] = input_settings['screensaver2_endhour']
    scheduler_settings['screensaver2']['endminute'] = input_settings['screensaver2_endminute']
    scheduler_settings['screensaver2']['type'] = input_settings['screensaver2_type']
    scheduler_settings['screensaver2']['enabled'] = input_settings['screensaver2_enabled']

    scheduler_settings['screensaver3']['hour'] = input_settings['screensaver3_hour']
    scheduler_settings['screensaver3']['minute'] = input_settings['screensaver3_minute']
    scheduler_settings['screensaver3']['endhour'] = input_settings['screensaver3_endhour']
    scheduler_settings['screensaver3']['endminute'] = input_settings['screensaver3_endminute']
    scheduler_settings['screensaver3']['type'] = input_settings['screensaver3_type']
    scheduler_settings['screensaver3']['enabled'] = input_settings['screensaver3_enabled']
	
    scheduler_settings['timezone'] = input_settings['timezone']

    with open('csv/scheduler.json', 'w') as f:
        json.dump(scheduler_settings,f)

    f = open('csv/last_updates.json', 'r')
    last_updates = json.load(f)
    f.close()

    last_updates['scheduler']['force'] = True

    f = open('csv/last_updates.json', 'w')
    json.dump(last_updates, f)
    f.close()

    return index()



@app.route("/saveScreensaverSettings", methods = ['PUT', 'POST'])
def saveScreensaverSettings():
	
    data = request.data.decode('utf-8')
    input_settings = json.loads(data)

    try:
        with open('clock_screensaver.json','r') as f:
            clock_screensaver = json.load(f)
    except:
        clock_screensaver = {"clock1": {"time_color": "White", "weekday_color": "Cyan", "date_color": "Blue", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "clock2": {"time_color": "Orange", "date_color": "White", "timezone": "Etc/GMT+4", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}, "world_clock": {"city_color": "White", "display_seconds": True, "display_pm": True, "12hour": True, "brightness": "10"}}

    clock_screensaver['clock1']['time_color'] = input_settings['clock1_timecolor']
    clock_screensaver['clock1']['weekday_color'] = input_settings['clock1_weekdaycolor']
    clock_screensaver['clock1']['date_color'] = input_settings['clock1_datecolor']
    clock_screensaver['clock1']['timezone'] = input_settings['clock1_timezone']
    clock_screensaver['clock1']['brightness'] = input_settings['clock1_brightness']
    clock_screensaver['clock1']['display_seconds'] = input_settings['clock1_displayseconds']
    clock_screensaver['clock1']['display_pm'] = input_settings['clock1_displaypm']
    clock_screensaver['clock1']['12hour'] = input_settings['clock1_12hour']

    clock_screensaver['clock2']['time_color'] = input_settings['clock2_timecolor']
    clock_screensaver['clock2']['date_color'] = input_settings['clock2_datecolor']
    clock_screensaver['clock2']['timezone'] = input_settings['clock2_timezone']
    clock_screensaver['clock2']['brightness'] = input_settings['clock2_brightness']
    clock_screensaver['clock2']['display_pm'] = input_settings['clock2_displaypm']
    clock_screensaver['clock2']['12hour'] = input_settings['clock2_12hour']

    clock_screensaver['world_clock']['city_color'] = input_settings['worldclock_citycolor']
    clock_screensaver['world_clock']['brightness'] = input_settings['worldclock_brightness']
    clock_screensaver['world_clock']['display_pm'] = input_settings['worldclock_displaypm']
    clock_screensaver['world_clock']['12hour'] = input_settings['worldclock_12hour']
    clock_screensaver['world_clock']['display_seconds'] = input_settings['worldclock_displayseconds']

    with open('clock_screensaver.json', 'w') as f:
        json.dump(clock_screensaver,f)
	
    return index()



@app.route("/setTop20or10", methods = ['PUT', 'POST'])
def setTop20or10():

    data= request.data.decode('utf-8')
    input_settings = json.loads(data)

    with open('csv/league_tables.json','r') as f:
        league_settings = json.load(f)

    if input_settings == 'Top 20':
        input_settings = 20
    elif input_settings == 'Top 10':
        input_settings = 10
    else:
        input_settings = 20

    league_settings['top20'] = input_settings

    f = open('csv/league_tables.json', 'w')
    json.dump(league_settings, f)
    f.close()

    return index()



@app.route("/deletePortfolioPositionCrypto", methods=["POST"])
def deletePortfolioPositionCrypto():
    value = request.data.decode('utf-8')
    value2 = json.loads(value)
    try:
        with open("csv/portfolio_crypto_settings.json") as f:
            data = json.load(f)
    except:
        data = {"symbols": {}}
    try:
        del data["symbols"][value2]
        with open('csv/portfolio_crypto_settings.json', 'w') as f:
            json.dump(data, f)
    except:
        pass
    return index()


@app.route("/deletePortfolioPosition", methods=["POST"])
def deletePortfolioPosition():
    value = request.data.decode('utf-8')
    value2 = json.loads(value)
    try:
        with open("csv/portfolio_settings.json") as f:
            data = json.load(f)
    except:
        data = {"symbols": {}}
    try:
        del data["symbols"][value2]
        with open('csv/portfolio_settings.json', 'w') as f:
            json.dump(data, f)
    except:
        pass
    return index()


@app.route("/fetchStockPortfolio", methods=["POST"])
def fetchStockPortfolio():
    value = request.data.decode('utf-8')
    value2 = json.loads(value)
    try:
        with open("csv/portfolio_settings.json") as f:
            data = json.load(f)
    except:
        data = {"symbols": {}}
    try:
        stock_pos_info = data['symbols'][value2]
    except:
        stock_pos_info = {}

    return (stock_pos_info)


@app.route("/fetchCryptoPortfolio", methods=["POST"])
def fetchCryptoPortfolio():
    value = request.data.decode('utf-8')
    value2 = json.loads(value)
    try:
        with open("csv/portfolio_crypto_settings.json") as f:
            data = json.load(f)
    except:
        data = {"symbols": {}}
    try:
        crypto_pos_info = data['symbols'][value2]
    except:
        crypto_pos_info = {}

    return (crypto_pos_info)


@app.route("/fetchCustomMsg", methods=["POST"])
def fetch_custom_msg():
    value = request.data.decode('utf-8')
    value2 = json.loads(value)
    try:
        with open("csv/message_settings.json") as f:
            data = json.load(f)
    except:
        data = {"feature": "Custom Messages", "speed": "medium", "speed2": "medium", "animation": "down", "title": False, "messages": [{"name": "welcome", "text": "Welcome to Fintic!", "text_colour": "White", "size": "Large", "background_colour": "Black"}, {"name": "get_started", "text": "To get started, connect your device to the \"Fintic Hotspot\" and access \"fintic.local:1024\" on your web browser. You can connect your ticker to Wi-Fi there.", "text_colour": "White", "size": "Small", "background_colour": "Black"}]}
    for i, each in enumerate(data['messages']):
        if each['name'] == value2:
            the_info = {'index': i, 'text': data['messages'][i]['text'], 'name': data['messages'][i]['name'], 'size':data['messages'][i]['size'], 'text_colour': data['messages'][i]['text_colour'], 'background_colour': data['messages'][i]['background_colour']}
            #the_info = data['messages'][i]
            break
        else:
            the_info = {}
    return (the_info)


@app.route("/sendMsgToJSON", methods = ['PUT', 'POST'])
def sendMsgToJSON():

    data= request.data.decode('utf-8')
    input_settings = json.loads(data)

    if input_settings['name'] != '' and input_settings['text'] != '':
        try:
            with open('csv/message_settings.json','r') as f:
                message_settings = json.load(f)
        except:
            message_settings = {"feature": "Custom Messages", "speed": "medium", "speed2": "medium", "animation": "down", "title": False, "messages": [{"name": "welcome", "text": "Welcome to Fintic!", "text_colour": "White", "size": "Large", "background_colour": "Black"}, {"name": "get_started", "text": "To get started, connect your device to the \"Fintic Hotspot\" and access \"fintic.local:1024\" on your web browser. You can connect your ticker to Wi-Fi there.", "text_colour": "White", "size": "Small", "background_colour": "Black"}]}
        message_settings['messages'].append(input_settings)
        with open('csv/message_settings.json', 'w') as f:
            json.dump(message_settings, f)

    return index()


@app.route("/updateSelectedMsg", methods=["PUT", "POST"])
def updateSelectedMsg():
    value = request.data.decode('utf-8')
    value2 = json.loads(value)
    try:
        with open("csv/message_settings.json") as f:
            data = json.load(f)
    except:
        data = {"feature": "Custom Messages", "speed": "medium", "speed2": "medium", "animation": "down", "title": False, "messages": [{"name": "welcome", "text": "Welcome to Fintic!", "text_colour": "White", "size": "Large", "background_colour": "Black"}, {"name": "get_started", "text": "To get started, connect your device to the \"Fintic Hotspot\" and access \"fintic.local:1024\" on your web browser. You can connect your ticker to Wi-Fi there.", "text_colour": "White", "size": "Small", "background_colour": "Black"}]}
    try:
        data['messages'][value2['index']]['name'] = value2['name']
        data['messages'][value2['index']]['text'] = value2['text']
        data['messages'][value2['index']]['text_colour'] = value2['text_colour']
        data['messages'][value2['index']]['size'] = value2['size']
        data['messages'][value2['index']]['background_colour'] = value2['background_colour']
        with open('csv/message_settings.json', 'w') as f:
            json.dump(data, f)
    except:
        pass

    return index()


@app.route("/savePromptStartStop", methods=["PUT", "POST"])
def savePromptStartStop():
    stop()
    time.sleep(0.1)
    start()
    return index()


@app.route("/scanNetworks", methods=["PUT", "POST"])
def scanNetworks2():
    try:
        output = subprocess.check_output(['sudo', 'iwlist', 'wlan0', 'scan'])
        output_str = output.decode('utf-8')
        lines = output_str.split('Cell')

        global networks
        networks = {}

        for line in lines:
            if 'ESSID:""\n' not in line and 'Scan completed' not in line:
                ssid = line.split('ESSID:')[1].split('\n')[0]
                ssid = ssid.replace('"', '', 1)
                ssid = ssid[::-1].replace('"', '', 1)[::-1]
                if 'AES' in ssid:
                    ssid = ssid.replace("AES", "CCMP")
                try:
                    group_cipher = line.split('Group Cipher : ')[1].split('\n')[0]
                    pair_cipher = line.split('Pairwise Ciphers (1) : ')[1].split('\n')[0]
                except:
                    group_cipher = ''
                    pair_cipher = ''
    #            quality = line.split('Quality=')[1].split('Signal level')[0].replace(" ", "")
                networks[ssid] = {'group_cipher': group_cipher, 'pair_cipher': pair_cipher}
    except:
        networks = {}
    return (networks)


@app.route('/upload_stocks', methods=['POST'])
def upload_file_stocks():
    file = request.files['file']
    filename = file.filename
    name, extension = os.path.splitext(filename)
    capitalized_name = name.upper()
    file_path = 'logos/stocks/' + capitalized_name + extension
    file.save(file_path)

    image = Image.open(file_path)

    if image.height > 32:
        new_width = int((32 / image.height) * image.width)
        resized_image = image.resize((new_width, 32))
        resized_image.save(file_path)
        resized_image.close()
    image.close()

    image = Image.open(file_path)

    if image.mode in ('RGBA', 'LA') or (image.mode == 'P' and 'transparency' in image.info):
        new_image = Image.new("RGBA", image.size, (0, 0, 0))
        new_image.paste(image, (0, 0), image)
        new_image.save(file_path)
        new_image.close()
    image.close()

    return index()


@app.route('/upload_crypto', methods=['POST'])
def upload_file_crypto():
    file = request.files['file']
    filename = file.filename
    name, extension = os.path.splitext(filename)
    capitalized_name = name.upper()
    file_path = 'logos/crypto/' + capitalized_name + extension
    file.save(file_path)

    image = Image.open(file_path)

    if image.height > 32:
        new_width = int((32 / image.height) * image.width)
        resized_image = image.resize((new_width, 32))
        resized_image.save(file_path)
        resized_image.close()
    image.close()

    image = Image.open(file_path)

    if image.mode in ('RGBA', 'LA') or (image.mode == 'P' and 'transparency' in image.info):
        new_image = Image.new("RGBA", image.size, (0, 0, 0))
        new_image.paste(image, (0, 0), image)
        new_image.save(file_path)
        new_image.close()
    image.close()

    return index()
	


if __name__ == "__main__":
    
    app.run(host='0.0.0.0', port=1024, debug=False) # the debuggger causes flickering 
        
   #sudo ./demo -D1 final.ppm -t 50 -m 25 --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=256 --led-slowdown-gpio=4 
