# class test

# this code is a quick and dirty test to see if I can get a class array for ticker, value, ssrow location for updating
# data quickly and efficienty.

import ezodf
import requests
import json

_TIINGO_flag = True

_TIINGO_KEY = '7dccb22a99e2e290a405c363117ea61a207e0662'
_TIINGO_url = 'https://api.tiingo.com/tiingo/daily/{}/prices'
_TIINGO_url_iex = 'https://api.tiingo.com/iex/{}'
_TIINGO_headers = {
    'Authorization': 'Token ' + _TIINGO_KEY,
    'Content-Type': 'application/json',
}


class ss:
    ticker = ''
    value = 0
    loc = ''



#
# is_none(x) function
#  This function looks at the value of the cell.value argument.  If it is None, it is set to zero.
#  If it is not None, then return the value of the argument.
#
def is_none(x):
    if x != None:
        return x
    else:
        return 00


doc = ezodf.opendoc('/Users/brtc/sw/fl_smf/pvt/FinancialPlanning-2018-TESTFILE.ods')
print("Opened the file")
sheet = doc.sheets['Value']

ddx = []
ticker_list = []
ticker_value = []



no_rows = sheet.nrows()



#ddx.append(ss())
#ddx[0].ticker = 'fpurx'
#ddx[0].value = 30.15
#ddx[0].loc = 0

#print('ddx is ', ddx[0].loc, ddx[0].ticker, ddx[0].value)


for index in range(0, no_rows):
    row = sheet.row(index)

    # get Ticker and present value from mss (master spreadsheet)

    ticker = is_none(row[0].value)
    price = is_none(row[1].value)

    ddx.append( ss() )

    if row[0].value != None:
        ticker_list.append(ticker)
        ticker_value.append(price)

        ddx[index].ticker = ticker
        ddx[index].loc = index
        print('DDX BEFORE TIINGO ', ddx[index].ticker,  ddx[index].loc)

        url = _TIINGO_url_iex.format(ticker)
        r = requests.get(url, headers=_TIINGO_headers)
        if r.status_code != 200:
            print("Bad request: status:",r.status_code, r.url)
#           ws.append([col.upper(),"NOT FOUND","NEVER"])
            continue

        rj = r.json()

        print ('***DEBUG*** ', ticker, url, price, row[0].value)

        if rj:

            try:
                print(r.status_code, ticker.upper(), rj[0]['timestamp'][0:10],rj[0]['timestamp'][11:16] ,rj[0]['tngoLast'])
                ddx[index].value = rj[0]['tngoLast']
                print('ddx[index] is ', ddx[index].loc, ddx[index].ticker, ddx[index].value)
                # ws.append( [col.upper(), rj[0]['tngoLast'],' ', rj[0]['timestamp'][0:16]])
            except KeyError:
                    print(r.status_code, ticker.upper(), "Couldn't get the ticker")
                    continue
            except IndexError:
                    print(r.status_code, r.url, ticker.upper(), "Badness here: Index Error")
                    # ws.append( [col.upper(), 'NO DATA', ' ', 'NO DATA'])
            continue

