#!/usr/bin/env python3
#=====================================================================================
# Retrieve a URL and only take Stock Quote from it
#=====================================================================================
import cgi                                          #import cgi module
import urllib.request                               #urllib.request module allows fetching of urls 
import cgitb
cgitb.enable()

print("Content-Type: text/html \n")                 #required http response header (w/ extra line)

elements = cgi.FieldStorage()                       #obtain the http for elements
symbol   = elements.getvalue('symbol') or 'AAPL'    #entry field, if empty use 'AAPL'            
 
url       = "https://www.cnbc.com/quotes/?symbol=" 

begin     = 0                                       #start searching   
searchFor = '"last"'                                #string to look for
offset    = 8                                       #the offset from the found string

msg  = ''                                           #Error message   - global variable

#-------------------------------------------------------------------------------------
# Function to validate entry fields
#-------------------------------------------------------------------------------------
def validate():
    global msg                                      #needed to modify global variable
                                                    #no need if access to global is read only
    if symbol=='':
        msg = '*** Please enter Stock Symbol ***'

#-------------------------------------------------------------------------------------
# Function to retrieve a URL from the web
#-------------------------------------------------------------------------------------
def getURL(url):
    global msg                                    #needed to modify global variable

    url2 = url + symbol

    try:
        resource = urllib.request.urlopen(url2)   #send the request
        page     = resource.read()                #read the returned data (in bytes type)
    except:
        msg   = "Could not retrieve URL"
        page  = ""
       
    page = page.decode('ascii', 'ignore')         #convert Byte type to String
                                                  #ignore if outside ascii value
    return(page)

#-------------------------------------------------------------------------------------
# Function to obtain the latest stock price from the web page
#-------------------------------------------------------------------------------------
def getQuote(page):
    global msg                                 #needed to modify global variable

    try:                                       #if not found
        found = page.index(searchFor,begin)    #find the search string, starting after x number of char
        start = found + offset                 #add the offset
        end   = page.index('"',start)          #look for ending "
        quote = page[start : end]              #substring 
    except:
        msg   = "Stock not found"
        quote = ""
       
#   print(quote)
    return(quote)

#-------------------------------------------------------------------------------------
# Function to display the page
#-------------------------------------------------------------------------------------
def display(quote):
    global msg                             #needed to modify global variable
                                           #no need if access to blobal is read only
    print('''
        <!DOCTYPE html>
        <html>
        <head>
        <title>Get URL</title>
        <style type="text/css">
            #Layer3 {position:relative; left:60px; top:10px; width:350px; height:110px;}
            .style4 {font-family: Arial, Helvetica, sans-serif; font-size:16px; font-weight: bold;}
        </style>
        </head>
        <body bgcolor='lightyellow'>
        <div id='Layer3'>

        <form METHOD=post ACTION=getURLquote.py>                
        <fieldset style='width:750'>
        <legend>Get a Stock Quote</legend> 

        <table border='0'>
        <tr>
        <td> Symbol </td>
    ''')
    print("<td><input type='text' id='symbol' name='symbol' size='20' value='" + symbol + "'>") 

    print('''
        </tr>
        <tr>
        <td></td>
        <td><input type='submit' value=' Last Price '>
    ''')
    if msg:
        print("<br><br> <font color='red'>" + msg + "</font></td>")		#print error message
    else:
        print("<br><br> <b>" + quote)          				#print the stock quote
        
    print('''
        </tr>
        </table>       
        </fieldset>
        </form>
        </div>
 ''')


#-------------------------------------------------------------------------------------
# Main code
#-------------------------------------------------------------------------------------

page  = ''
quote = ''

if elements:                                    #if data was entered in the form 
    validate()                                  #validate entered data                                
    page  = getURL(url)                         #retrieve the url
    quote = getQuote(page)                      #obtain the stock's latest price

display(quote)                                  #call display function





#=== link to see the python code ================================================
import os
import sys
sys.path.insert(0,'/home/s/sultans/web/python/demo')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#================================================================================