'''
updated Mar 23  to add auto install from chrome driver
Renamed from WebandImagetoVide0.py

'''
'''
##  20 Oct  19 ,working version - modified version of  "WebToImageToVideo2.py"   modded to do html and images
###  Opens websites, copys screenshot to Image file.  Open Image File adds QRcode to all snips, creates video from images,
####  plays video every x mins
### Seleniium need correct version of ChromeDriver for chrome browser, download and replace in correct file
## chromedriver/
'''
import qrcode
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from time import sleep
from datetime import datetime
import csv
import cv2
import numpy as np
import glob
import chromedriver_autoinstaller

chromedriver_autoinstaller.install()  # Check if the current version of chromedriver exists
                                      # and if it doesn't exist, download it automatically,
                                      # then add chromedriver to path

driver = webdriver.Chrome()



options = Options()
options.headless = True
options.add_argument("window-size=1670,1000")
#options.add_argument("headless") 

UrlRun=0
ImageRun=0
       

def Url_Convert(UrlRun):
    #if (int(min_last))==0 and UrlRun==0:
    if UrlRun==0:
        UrlRun=1
        print (' start UrlConvert ....')
        #print ('run number  ' + str(count))
        driver = webdriver.Chrome(options=options)#needs correct version
        for m in range (1):
            print ('m is  ' + str(m))

            now = datetime.now()

            DirStr="./snip"
            QRStr="./QRimage"
            

            #******************************
            #  start here with loop for urls
            contents = []
            with open('urlfile.csv', 'r') as csvf: # Open file in read mode
                urls = csv.reader(csvf, delimiter='\t') #  delimiter='\t' ensure correct clsoure evenon exception
                for url in urls:
                    contents.append(url) # Add each url to list contents

            print (contents)
            if len(contents)<1:
                print(' no urls contained in file urlfile.csv')
                
            for i in range (len(contents)):
                try:
                    turl = str(contents[i])
                    turl= (turl[:-2])
                    turl=(turl[2:])
                    print(turl)
                    time.sleep(1)
                    driver.get(turl)
                    print ('got   ' + turl)
                    driver.save_screenshot((DirStr+str(i)+".png"))    # DirStr="C:\Python36\carousel\snip"
                    sleep(1)
                    print ('saved as....', (DirStr+str(i)+".png"))

                except:
                    turl = str(contents[i])
                    turl= (turl[:-2])
                    turl=(turl[2:])
                    print(turl)
                    print ('Failed to access ' + turl)
                    
                
        print ('exited m loop')
        driver.quit()
        
    sleep(1)
    print ('point 1')


def Add_QrCodes():
            # loop through all images, for each image create and add QRCode and create video
    # find and loop
    print (' start QrCode ....')
    DirStr="./snip"
    QRStr="./QRimage"
    ImgArray=[]
                
    for filename in glob.glob(DirStr +"*.png"):
        ImgArray.append(filename)
        print ('Array len is ....', len(ImgArray))
        #print (ImgArray)
    
    for i in range (len(ImgArray)):
        f_string=(ImgArray[i])
        print (f_string)
        img = cv2.imread(ImgArray[i])
        heightstr = str(np.size(img, 0))
        widthstr = str(np.size(img, 1))
        
    #*******   Create QR Code   **********
        # get time
        dt_string = now.strftime("%d/%m/%Y %H:%M")
        print("date and time =", dt_string)
        size_string=(heightstr + "," + widthstr)

           # Create qr code instance
        qr = qrcode.QRCode(
            version = 4,   # 1 is 21x21, 2 is 25x25, 4 is 33x33 @ ERRCC L gives 114 char, @ M 90 char
            error_correction = qrcode.constants.ERROR_CORRECT_L, 
            box_size = 10,
            border = 4,
        )

        # The data that you want to store
        data = f_string+ ","+ size_string + "," + dt_string  # ";" +turl +
        print ('QR String is......', data)
        qr.add_data(data)
        qr.make(fit=False)  #  make tru to autofit

        # Create an image from the QR Code instance
        qrimg = qr.make_image()

        # Save it somewhere, change the extension as needed:
        qrimg.save("TEMP.png")             #   

    #************************************
    #*********   combine images *********
        QRimg=cv2.imread("TEMP.png")
        QRimg=cv2.resize(QRimg,(250,250))

        tempimg = cv2.imread(ImgArray[i])
        #tempimg = cv2.resize(tempimg,(1650,775))
        h1, w1 = tempimg.shape[:2]
        h2, w2 = QRimg.shape[:2]

        #create empty matrix
        CombinedImage = np.zeros((max(h1, h2), w1+w2,3), np.uint8)

        #combine 2 images
        CombinedImage[:h1, :w1,:3] = tempimg
        CombinedImage[:h2, w1:w1+w2,:3] = QRimg
        SaveString = (QRStr+str(i)+".png")
        print ('SaveString is .....' + SaveString)

        cv2.imwrite ( SaveString, CombinedImage)  #
        sleep(1)
        #print (i)
        
                
        # create video file from images
def Create_Video():
    multip = 1
    img_array = []

    width=1920
    height=1000

    Filestr='./QRimage'

    out = cv2.VideoWriter('project2.avi',cv2.VideoWriter_fourcc(*'DIVX'), 1, (width,height), True)
    #for i in range(1,6):

    ImgArray=[]
                
    for filename in glob.glob(Filestr +"*.png"):
        ImgArray.append(filename)
        print ('Video Array len is ....', len(ImgArray))
    
    for i in range (len(ImgArray)): 
        stri=str(i)
        print ('File is ....', (Filestr + stri +'.png'))
        img= cv2.imread(Filestr + stri +'.png')
        img= cv2.resize(img,(width,height))

        print (Filestr + stri +'.png')
        for m in range(multip):
            out.write(img)
        if i == 1:
            out.write(img)   # extra frames to allow capture on start
            out.write(img)
    out.release()
        
    # ************************************************

    
    #************ play video evry 5 mins  **************
def Play_Video():
    print ('entering video ')
    #if (int(min_last))==5:
    #if int(min_last) % 2 > 0:
    cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
    cv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

    #cv2.namedWindow('frame',cv2.WINDOW_NORMAL) # this works
    #cv2.resizeWindow('frame', width,height)  # this works
    cap = cv2.VideoCapture('project2.avi')
    while True:
        ret, frame = cap.read()
        
        if not ret:
            break
        
        cv2.imshow('frame',frame)
        if cv2.waitKey(25) & 0xFF == ord('q'):
             break
        sleep(1)

    cap.release()
    cv2.destroyAllWindows()

    
###  main loop ##
while(True):
    now = datetime.now()
    min_str = now.strftime("%M")
    print (min_str)

    min_last=min_str[1]
    print ('min last is ' + min_last)

    if int(min_last) % 2==0:  #  even
    #if int(min_last)==0:
        UrlRun=0
        ImageRun=0
        Url_Convert(UrlRun)
        Add_QrCodes()
        Create_Video()

    if int(min_last) % 2 > 0: # odd
    #if (int(min_last))==5:
        Play_Video()

    sleep(200)
