import json
import sys
import base64
import time
from kiteconnect import KiteConnect

from __config import CONFIG
from __mySqlConnector import MYSQLCONNECTOR

def get_access_token():

    with open(CONFIG.token_file, 'r') as file:
        access_token = file.read()

    return access_token


class POPULATEDATA():

    def __init__(self, inputData):
        inputData = json.loads( base64.b64decode(inputData) ) 
        self.category = inputData["category"]

        self.kite = KiteConnect(api_key=CONFIG.api_key)
        self.kite.set_access_token( get_access_token() )

        self.myConnector = MYSQLCONNECTOR()

        self.debug = ''

    def getClosePrice(self, instrument):
        price = self.kite.quote(instrument)[instrument]['ohlc']['close']
        return price


    def populate(self):
        #price = self.getClosePrice('NSE:NIFTY 50')
        symbolsList = self.myConnector.getEmptyDataRows(self.category)
        for index, symbol in enumerate(symbolsList, start=1):
            symbol = symbol[0]
            if "SENSEX" in symbol:
                tradingSymbol = 'BFO:' + symbol
            else:
                tradingSymbol = 'NFO:' + symbol
            try:
                price = self.getClosePrice(tradingSymbol)
            except:

                try:

                    if 'FINNIFTY25OCT' in tradingSymbol:
                        tradingSymbol = tradingSymbol.replace('FINNIFTY25OCT', 'FINNIFTY25SEP')
                    elif 'FINNIFTY25SEP' in tradingSymbol:
                        tradingSymbol = tradingSymbol.replace('FINNIFTY25SEP', 'FINNIFTY25AUG')
                    
                    
                    price = self.getClosePrice(tradingSymbol)
                
                except:
                    if 'FINNIFTY25SEP' in tradingSymbol:
                        tradingSymbol = tradingSymbol.replace('FINNIFTY25SEP', 'FINNIFTY25AUG')
                    price = self.getClosePrice(tradingSymbol)


            self.myConnector.setPriceDataRow(self.category, symbol, price)
            if index % 5 == 0:  
                time.sleep(0.25)  

        

        

    def getDebug(self):
        return str(self.debug)



if __name__== "__main__":

    returnDict = {}
    returnDict['status'] = 'OK'
    returnDict['remarks'] = ''

    try:
        helper = POPULATEDATA(sys.argv[1])
    except Exception as e:
        returnDict['status'] = 'KO'
        returnDict['remarks'] = str(e)
        print (json.dumps(returnDict))
        sys.exit()

    try:
        returnDict['quote'] = helper.populate()
    except Exception as e:
        returnDict['status'] = 'KO'
        returnDict['remarks'] = str(e) + ' ' + helper.getDebug()

    print (json.dumps(returnDict))


    