#!/usr/bin/python3
# -*- coding: utf-8 -*-


import os
import json
import requests

# Load config and cache
# ----------

with open('/home/sahi_no/.config/i3/scripts/mvgblock/mvgconfig.json', 'r') as file:
    config = json.load(file)

with open('/home/sahi_no/.config/i3/scripts/mvgblock/mvgcache.json', 'r') as file:
    cache = json.load(file)

stationIndex= int(cache['station_index'])
departureIndex = int(cache['departure_index'])
enabled = cache['enabled']
filtered = cache['filtered']
stationName= config['stations'][stationIndex]['name']
stationID= config['stations'][stationIndex]['id']
directions= config['stations'][stationIndex]['directions']
lines= config['stations'][stationIndex]['lines']
departures= cache['departures']

oldDepartureIndex = departureIndex

# ----------
def blockEvent():
    global enabled
    global filtered
    global departureIndex

    event = '0'
    try:
        event = os.environ['BLOCK_BUTTON']
    except KeyError:
        event = '0'

#   event = '1'

    if event == '1': #Left-click
        ## toggle display
        enabled = not enabled
        ## set index to zero
        departureIndex = 0
    elif event == '2': #Middle-click
        ## toggle filter
        filtered = not filtered
        ## set index to zero
        departureIndex=0
    elif event == '3': #Right-click
        ## change station
        changeStationIndex()
        ## set index to zero
        departureIndex= 0
    elif event == '4': #Scroll-up
        ## change index(negative)
        changeDepartureIndex(-1)
    elif event == '5': #Scroll-down
        ## change index(positive)
        changeDepartureIndex(+1)
    elif enabled == True:
        departureIndex = 0

def changeStationIndex():

    global stationIndex
    global stationName
    global stationID
    global directions
    global lines


    stationIndex += 1
    if stationIndex == len(config['stations']):
        stationIndex = 0

    stationName= config['stations'][stationIndex]['name']
    stationID= config['stations'][stationIndex]['id']
    directions= config['stations'][stationIndex]['directions']
    lines= config['stations'][stationIndex]['lines']

def changeDepartureIndex(iterate):

    global departureIndex

    if departureIndex + iterate == len(cache['departures']) or departureIndex + iterate < 0:
        pass
    else:
        departureIndex += iterate


def load(filtered):

    global departures 

    headers = {"Accept-Language": "de;q=0.5"}

    # payload = json.loads(subprocess.check_output(["curl", "www.mvg.de/api/fahrinfo/departure/" + stationID]))
    departureRequest = requests.get("https://www.mvg.de/api/fahrinfo/departure/" + stationID, headers=headers)
    timeRequest = requests.get("https://www.mvg.de/clockService/currentDate", headers=headers)

    payload = departureRequest.json()["departures"]
    currentTime = int(timeRequest.text)

    departures = []

    for departure in payload:
        fDeparture = {}
        fDeparture["line"]= departure["label"]
        fDeparture["destination"]= departure["destination"]
        
        departureTime = departure["departureTime"]

        fDeparture["minutes"] = (departureTime - currentTime + 2 * 60 * 60 * 1000) // 1000 // 60
        
        if fDeparture["minutes"] > 0:
            departures.append(fDeparture)
    
    if filtered:
        return filter(departures)
    else:
        return departures 

def filter(departures):

    global directions
    global lines

    filteredData = []
    if departures == None:
        return []
    for departure in departures:
        if departure['destination'] in directions:
            if departure['line'] in lines:
                filteredData.append(departure)

    return filteredData

def printer(data):

    writeCache(data)

    if data == [] or data == None:
        frag = []
        frag.append('<span color="#DC143C">')
        frag.append('</span>')
        output = ':: NO DEPARTURE DATA AVAILABLE FOR %s ::' % stationName
        if 'straße' in output:
            output = output.replace('straße', 'str.')
        if 'ß' in output:
            output = output.replace('ß', 'ss')
        output = output.upper()
        output = frag[0] + output + frag[1]
        outputshort = frag[0] + ':: NO DEPARTURE DATA AVAILABLE ::' + frag[1]
        print(output)
        print(outputshort)
        exit()

    toShow = data[departureIndex]
    if toShow['minutes'] > 15:
        color = '#C0C0C0'
    elif toShow['minutes'] >= 10:
        color = '#00FF00'
    elif toShow['minutes'] >= 8:
        color = '#FFFF00'
    elif toShow['minutes'] >= 5:
        color = '#FFA500'
    elif toShow['minutes'] < 5:
        color = '#FF0000'
    #FF0000 RED
    #FFA500 ORANGE
    #FFFF00 YELLOW
    #00FF00 GREEN

    frag = []
    frag.append('<span color="#C0C0C0">')
    frag.append('</span>')
    frag.append('<span color="' + color + '">')
    frag.append('</span>')
    frag.append('<span color="#C0C0C0">')
    frag.append('</span>')

    output = ('Line %s to %s DEPARTS IN %s MINUTE(S) FROM %s ') % (toShow['line'], toShow['destination'], toShow['minutes'], stationName)
    output = output.lower()

    if 'straße' in output:
        output = output.replace('straße', 'str.')
    if 'ß' in output:
        output = output.replace('ß', 'ss')
    output = output.upper()

    loc = []
    loc.append(output.find('TO '))
    loc.append(output.find('DEPARTS'))
    loc.append(output.find(' IN '))
    loc.append(output.find('FROM'))

    outputlong = frag[0] + output[:loc[2]] + frag[1] + frag[2] + output[loc[2]:loc[3]] + frag[3] + frag[4] + output[loc[3]:] + frag[5]

    outputshort = frag[0] + output[:loc[0]] + output[loc[1]:loc[2]]  + frag[1] + frag[2] + output[loc[2]:loc[3]] + frag[3] + frag[4] + output[loc[3]:] + frag[5]

    print(outputlong)
    print(outputshort)

def writeCache(data):

    global stationIndex
    global departureIndex
    global enabled
    global filtered

    cache = {}

    cache['departures']= data
    cache['station_index']= stationIndex
    cache['departure_index']= departureIndex
    cache['enabled']= enabled
    cache['filtered']= filtered

    with open('/home/sahi_no/.config/i3/scripts/mvgblock/mvgcache.json', 'w') as file:
        json.dump(cache, file, indent=2)

blockEvent()
if not enabled:
    print('<span color="#FFA500">:: VIEW DEPARTURES ::</span>')
    data = {}
    writeCache(data)
    exit()
data = {}
if oldDepartureIndex != departureIndex:
    data = cache['departures']
else:
    data = load(filtered)

printer(data)
     
