#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# Rev 2.0 RKN 08/01/2016
# Rev 1.0 RKN Nov 2015
# A file sharestoget.txt lists what files are to be monitored.
# Prog collects shares info from internet at interval set by schedule.
# Stores current share price in an individual txt file for each share.
# Each record saved has an index marker.

import ystockquote
import schedule
import time
import shutil
import datetime

base = "SharesData/"
#base = "TestSharesData/"

filename = base + "sharestoget.txt"
tempfile = base + "tempfile.txt"

print filename
print tempfile
print "Waiting for scheduled collection"

def copyFile(srcf, destf):
    try:
        shutil.copy(srcf, destf)
    except shutil.Error as e:
        print ('Error: %s' %e)
    except IOError as e:
        print('Error: %s' %e.strerror)




def job():
    savedshareslist = open(filename, 'r')
    tempshareslist = open(tempfile, 'w')



    sharesToGet = []

    for line in savedshareslist:
        
        #print "raw line", str(line)
        lengthofline = len(line)
        # print "lengthofline" , lengthofline
        commapos = line.find(",")
        commapos2= line.find(",",commapos+ 1)
        
        indexpoint = line[commapos2 + 1:(lengthofline-1)]

        buyprice = str(line[commapos + 1 :commapos2])
        #print "buyprice", buyprice
        line = line[0:(commapos-1)]
        
        #print "modified string" , line

        indexpointer = int(indexpoint) + 1
        
        #print "index pointer" , indexpointer

        datafortemp = str(line) +" ," + str(buyprice)+ "," + str(indexpointer)
        tempshareslist.write(datafortemp + "\n")
        
        sharesToGet=(str(line))

        #print "share to get" , sharesToGet
        #print " "

        
        tickerSymbol = line
        allInfo = ystockquote.get_all(tickerSymbol)
        av1 = " "
        av2 = " "
        print " "
        print tickerSymbol + " Price = " + allInfo["price"]
        
        savefilename = base + line + ".txt"
        result = open(savefilename, 'a')
        #now = time.ctime()
        
        now = str(datetime.datetime.now())
        now = now[0:10]
        datatowrite = str(indexpointer) + ", " + allInfo["price"] + "," +  str(buyprice) + ", " + str(av1)+ ", " + str(av2) + ", " + str(now)+ ", " + str(line) 
        result.write(datatowrite + "\n")
        result.close()
        

    tempshareslist.close()
    savedshareslist.close()
    
    copyFile(srcf =str(tempfile),destf= str(filename))
    print " "
    print "files swapped " + str(now)
    print "Waiting for scheduled collection"


    
schedule.every().friday.at("18:45").do(job)
#schedule.every(1).minutes.do(job)


timecount = 0

while True:
    schedule.run_pending()
    time.sleep(1)
    if timecount > 60:
        print str(datetime.datetime.now())
        timecount = 0
    else:
        timecount = timecount + 1



### END OF LISTING  ###
