from datetime import datetime
import numpy as np
import cv2
#from decimal import Decimal
import math

strExeBeginTime=datetime.now().strftime("%H:%M:%S")

iWidth=3400 # pixels
iHeight=2380 # pixels
fFPS=24 # frames/second

# total 131.968 seconds
# want 134 seconds
iIdxFrameBegin=1
iIdxFrameEnd=134*fFPS

oEncode=cv2.VideoWriter_fourcc(*'mp4v') # 指定視訊編碼
oOut=cv2.VideoWriter( '../videos/tb14_only_video.mp4',oEncode,fFPS,(iWidth,iHeight),True)

class TheData:
  def __init__(self,straItem):
    self.strDescription=straItem[0]
    self.fSecs1=float(straItem[1])
    self.fSecs2=float(straItem[2])
    self.strBGFileName=straItem[3].strip()
    self.strFGFileName="fg"+(straItem[3].strip())[2:]
    
    # 由上而下 或 由左而右 不一定，全看 beg -> end
    self.fBegX1=float(straItem[4])
    self.fBegY1=float(straItem[5])
    self.fBegX2=float(straItem[6])
    self.fBegY2=float(straItem[7])
    '''
    if self.fBegX1>self.fBegX2:
      self.fBegX1,self.fBegX2=self.fBegX2,self.fBegX1
      self.fBegY1,self.fBegY2=self.fBegY2,self.fBegY1
    '''  
    self.fEndX1=float(straItem[8])
    self.fEndY1=float(straItem[9])
    self.fEndX2=float(straItem[10])
    self.fEndY2=float(straItem[11])
    '''
    if self.fEndX1>self.fEndX2:
      self.fEndX1,self.fEndX2=self.fEndX2,self.fEndX1
      self.fEndY1,self.fEndY2=self.fEndY2,self.fEndY1
    '''
    
# 讀取檔案內容
oFile=open('20220608_data_from_excel_utf8.txt','r',encoding='UTF-8')
oContent=oFile.read()
oFile.close()

# 拿掉註解行
straSourceLine=("\n".join(("\n".join(oContent.split("\r\n"))).split("\r"))).split("\n")
straWantedLine=[]
for i in range(0,len(straSourceLine)):
  straItem=straSourceLine[i].split("\t")
  iItems=0
  for j in range(0,len(straItem)):
    if straItem[j].strip()!="":
      iItems+=1
  if iItems>=12:
    straWantedLine.append(TheData(straItem))

iMaxLenOfNum=len(str(iIdxFrameEnd)) # 數字總共幾位數
iIdxFrameBegin-=1 # base 0
iIdxFrameEnd-=1 # base 0

iIdxLastTime=-1

for iIdxFrame in range(iIdxFrameBegin,iIdxFrameEnd+1):
  
  fCurrentSeconds=(iIdxFrame+1)/fFPS
  strCurrentBGFileName=""
  strCurrentFGFileName=""
  iIdxDataBegin=-1
  iIdxDataEnd=-1
  
  # 尋找這個頁面的最後一筆
  
  if iIdxLastTime!=-1: iIdxTmpBegin=iIdxLastTime
  else: iIdxTmpBegin=0
  
  for iIdxData in range(iIdxTmpBegin, len(straWantedLine)):
    if fCurrentSeconds<straWantedLine[iIdxData].fSecs1:
      iIdxDataEnd=iIdxData-1
      if iIdxDataEnd<0: iIdxDataEnd=0
      strCurrentBGFileName=straWantedLine[iIdxDataEnd].strBGFileName
      strCurrentFGFileName=straWantedLine[iIdxDataEnd].strFGFileName
      break
  
  if iIdxDataEnd==-1:
    iIdxDataEnd=len(straWantedLine)-1
    strCurrentBGFileName=straWantedLine[iIdxDataEnd].strBGFileName
    strCurrentFGFileName=straWantedLine[iIdxDataEnd].strFGFileName
    
  # 尋找這個頁面的第一筆
  if iIdxLastTime!=-1:
    iIdxDataBegin=iIdxLastTime
  else:
    for iIdxData in range(iIdxDataEnd,-1,-1):
      if strCurrentBGFileName==straWantedLine[iIdxData].strBGFileName:
        iIdxDataBegin=iIdxData
      else:
        break
  
  # nmomtf
  #print("iIdxFrame="+str(iIdxFrame), "iIdxDataBegin="+str(iIdxDataBegin), "iIdxDataEnd="+str(iIdxDataEnd))
  
  # 繪製這個 frame
  
  for iIdxCB in range(iIdxDataBegin,iIdxDataEnd+1):
    if straWantedLine[iIdxCB].fSecs1==straWantedLine[iIdxCB].fSecs2:
      
      oFG=cv2.imread('../images/'+strCurrentFGFileName,cv2.IMREAD_COLOR)
      oBG=cv2.imread('../images/'+strCurrentBGFileName,cv2.IMREAD_COLOR)
      
    else:
      
      # 方向 beg -> end
      # 目前先是矩形好了，未來才用平行四邊形
      
      '''
      fX=straWantedLine[iIdxCB].fBegX1
      fY=straWantedLine[iIdxCB].fBegY1
      fW=straWantedLine[iIdxCB].fBegX2-straWantedLine[iIdxCB].fBegX1
      fH=straWantedLine[iIdxCB].fEndY1-straWantedLine[iIdxCB].fBegY1
      
      if fCurrentSeconds<straWantedLine[iIdxCB].fSecs2:
        fH=fH*(fCurrentSeconds-straWantedLine[iIdxCB].fSecs1)/(straWantedLine[iIdxCB].fSecs2-straWantedLine[iIdxCB].fSecs1)
      
      x1=math.floor(fX)
      y1=math.floor(fY)
      x2=math.floor(fX+fW)
      y2=math.floor(fY+fH)
      '''
      
      fBegX1=straWantedLine[iIdxCB].fBegX1
      fBegY1=straWantedLine[iIdxCB].fBegY1
      fBegX2=straWantedLine[iIdxCB].fBegX2
      fBegY2=straWantedLine[iIdxCB].fBegY2
      fEndX1=straWantedLine[iIdxCB].fEndX1
      fEndY1=straWantedLine[iIdxCB].fEndY1
      fEndX2=straWantedLine[iIdxCB].fEndX2
      fEndY2=straWantedLine[iIdxCB].fEndY2
      fNewEndX1=fEndX1
      fNewEndY1=fEndY1
      fNewEndX2=fEndX2
      fNewEndY2=fEndY2

      if fCurrentSeconds<straWantedLine[iIdxCB].fSecs2:
        fTheRatio=(fCurrentSeconds-straWantedLine[iIdxCB].fSecs1)/(straWantedLine[iIdxCB].fSecs2-straWantedLine[iIdxCB].fSecs1)
        fNewEndX1=fTheRatio*(fEndX1-fBegX1)
        fNewEndY1=fTheRatio*(fEndY1-fBegY1)
        fNewEndX2=fTheRatio*(fEndX2-fBegX2)
        fNewEndY2=fTheRatio*(fEndY2-fBegY2)
      
      x1 = math.floor(min(fBegX1, fBegX2, fNewEndX1, fNewEndX2))
      y1 = math.floor(min(fBegY1, fBegY2, fNewEndY1, fNewEndY2))
      x2 = math.floor(max(fBegX1, fBegX2, fNewEndX1, fNewEndX2))
      y2 = math.floor(max(fBegY1, fBegY2, fNewEndY1, fNewEndY2))
      
      oBG[y1:y2,x1:x2]=oFG[y1:y2,x1:x2]
  
  #strNewFileName='frame'+str(iIdxFrame+1).zfill(iMaxLenOfNum)+'.jpg'
  #cv2.imwrite('frames/'+strNewFileName, oBG, [cv2.IMWRITE_JPEG_QUALITY, 100])
  oOut.write(oBG)
  print("Frame "+str(iIdxFrame)+" / "+str(iIdxFrameEnd+1)+" finished.")
  
  iIdxLastTime=iIdxDataEnd

oOut.release()
print("All finished!")

strExeEndTime=datetime.now().strftime("%H:%M:%S")
print(strExeBeginTime, strExeEndTime)