import os
import sys
from selenium import webdriver
import time
import threading
from PIL import ImageGrab
from moviepy.editor import ImageSequenceClip

fileid = 0      #csv文件编号  详见 fileinfo.js
picpath =  r"pic\\%d" % fileid
videopath =  r"video"
screenshotArea = (635, 338, 1285, 828)  #屏幕截图范围 （起点x坐标，起点y坐标, 终点x坐标, 终点y坐标)
imageList = []

driver = None
totalTime = 0   # 心跳记录的总时长 秒
endFlag = 0     # 0:未开始 1:已开始 2:已结束 
frameIndex = 0
iswork = 0
threadNum = 0
intverTime = 0.03 # 截图间隔时间 秒
i = 0

def save_screenshot():
    global driver, fileid, picpath, screenshotArea, imageList, totalTime, endFlag, frameIndex, iswork, threadNum, intverTime, i

    try:
        if iswork == 0:
            return
        threadNum += 1 

        t = threading.Timer(intverTime, save_screenshot)  # 帧率: 25张/秒
        t.start()

        if i >= 25:
            i = 0
        if i == 0:
            # totalTime = int(driver.find_element_by_id("totalTime").get_attribute('value'))
            endFlag = int(driver.find_element_by_id("endFlag").get_attribute('value')) 
        i += 1
        # print("[%s] %d" % (time.strftime('%H:%M:%S', time.localtime(time.time())), frameIndex))
        # print("[%s][%d] %d / %d" % (time.strftime('%H:%M:%S', time.localtime(time.time())), frameIndex, rowNum, rsCount))

        if endFlag == 1:
        # if intverTime * i <= totalTime:
            frameIndex += 1
            # file = r"%s\\%s_%s_%d.png" % (picpath, ('00000' + str(frameIndex))[-5:], time.strftime('%H%M%S', time.localtime(time.time())), i)
            file = r"%s\\%s.png" % (picpath, ('00000' + str(frameIndex))[-5:])
            imageList.append(file)
            im = ImageGrab.grab(screenshotArea)
            im.save(file)
            print("save_screenshot: " + file)
        elif endFlag == 2:
            iswork = 0

        threadNum -= 1
        if iswork == 0 and threadNum <= 0:
            print("save_screenshot finished !!")
            print("threadNum: %d" % threadNum)

            driver.close()
            driver.quit()
            print("============ makeVideo ============")
            saveVideo()

    except BaseException as msg:
        print("[err] %s" % msg)
        threadNum -= 1
        iswork = 0
        if iswork == 0 and threadNum <= 0:
            driver.close()
            driver.quit()

def saveVideo():
    global fileid, videopath
    clip = ImageSequenceClip(imageList, fps = 25)
    clip.write_videofile("%s\\%s.mp4" % (videopath, fileid), codec="libx264", bitrate="200000")

def main():
    global driver, picpath, iswork
    try:
        if not os.path.exists(picpath):
            os.makedirs(picpath)
            
        driver = webdriver.Chrome(r"chromedriver.exe")
        picture_url = "http://localdata/?f=%d" % fileid

        driver.maximize_window()
        driver.get(picture_url)
        # driver.refresh()

        time.sleep(0.5)

        iswork = 1
        save_screenshot()

        # driver.close()
        # driver.quit()
    except BaseException as msg:
        print("[err] %s" % msg)
        driver.close()
        driver.quit()


if __name__ == '__main__':
    paramNum = len(sys.argv)
    if paramNum != 2:
        print("param err! please input fileid.")
        exit()

    # sys.argv[0] 表示脚本名
    fileid = int(sys.argv[1])      #csv文件编号  详见 fileinfo.js
    picpath =  r"pic\\%d" % fileid
    
    main()
