#############################################################
 # 
 # FILE:        SeqAcquisition.py
 # DATE:        11/10/2021
 # COMPANY:     BitFlow, Inc.
 # DESCRIPTION: A simple example demonstrating sequential acquisition 
 #              using a BitFlow board. The program allocates and acquires
 #              frames to ten buffers and gives the option to save these 
 #              frames to the working directory.
 #
#############################################################
import platform
import os
if(platform.system() == 'Windows'):
    import sys
    import msvcrt
    if (sys.version_info.major >= 3 and sys.version_info.minor >= 8):
        #Following lines specifying, the location of DLLs, are required for Python Versions 3.8 and greater
        os.add_dll_directory("C:\BitFlow SDK 6.5\Bin64")
        os.add_dll_directory("C:\Program Files\CameraLink\Serial")
import BFModule.BufferAcquisition as Buf
import BFModule.Display as Disp
import time
def main():
    print('Sequential Acquisition Example')
    print('---------------------------------')
    
    numBuffers = 10
    SeqAq = Buf.clsSeqAcquisition()
    #Call Open board function by showing the Board select dialog
    SeqAq.Open()
    #Allocate the requested number of buffers
    BufArr = SeqAq.BufferSetup(numBuffers)
    #Setup acquisition using the default options
    SeqAq.AqSetup(Buf.SetupOptions.setupDefault)
    #Start acquisition
    SeqAq.AqControl(Buf.AcqCommands.Start, Buf.AcqControlOptions.Wait)
    #Wait until all 10 frames have been acquired
    print ('Acquiring frames . . .')
    SeqAq.WaitSequenceDone(15000)
    
    print('Done.')
    #Create display surface
    dispSurf = Disp.clsDisp(SeqAq)
    
    dispSurf.Open()
    
    print('\nDisplaying images . . .')
    print('Hit: \n    \'L\' to loop through all images once, \n    \'N\' to loop through one image at a time')
    
    flag = False
    loop = False
    while(not(flag)):
        val = input() 
        if (val.upper() == 'L'):
            loop = True
            flag = True
        elif(val.upper() == 'N'):
            loop = False
            flag = True
        else:
            print('Invalid Entry.')
            loop = False
            flag = False
    for i in range(0, numBuffers):
        print('\tDisplaying frame', (i+1), 'of ', numBuffers, '\r', end="")
        dispSurf.Update(BufArr[i])
        if(loop):
            time.sleep(0.25)
        else:
           input() 
    val = input('\n\nSave images? (Y/N): ')
    if (val.upper() == 'Y'):
        in1 = input('Enter the buffer number to save (\'A\' to save all images): ')
       
        try:
            if(in1.strip().isdigit()):
                i = int(in1)
                if(i<numBuffers):
                    #FileName = os.getcwd() + '\\' + 'Image_'+ str(i) + '.BMP'
                    FileName = 'Image_'+ str(i) + '.tiff'
                    SeqAq.WriteBuffer(FileName, i)
                    print('Image saved as: ', FileName)
                else:
                    print('Invalid entry. Buffer number has to be between 0 and ', numBuffers)
            elif(in1.isalpha()):
                if(in1.upper() == 'A'):
                    FileName = os.getcwd() + '/' + 'Image.TIFF'
                    SeqAq.WriteBuffers(FileName, 0, numBuffers)
                    print('Images saved in: ', os.getcwd())
                    pass
                else:
                    print('Invalid entry.')
            else:
                print('Invalid entry.')
        except Exception as e:
            print("\nImage save operation failed.")
            print(e)
    else:
        print("")
    print("\nClosing Display.")
    #Close display and free resources
    dispSurf.Close()
    #Deallocate buffers
    SeqAq.BufferCleanup()
    #Close the board
    SeqAq.Close()
if __name__ == "__main__":
    main()