#!/cygdrive/c/python34/python
#
#  program to delete image files by moving them to a temp directory
#
import pdb
import subprocess
from bird_utils import ls_cmd
from bird_utils import findit
import openpyxl
from openpyxl import load_workbook
import send2trash

# routine for reading in the inventory and place databases
# a dictionary is created with the date and the imagename the key (yyyymm+imagename)
# The bird/place name are the entries.
def read_excel (dbs):
    files = ["inventory.xlsx", "place.xlsx"]
    i_sheet = ["inventory", "place"]
    for file in files:
        wb = openpyxl.load_workbook(file, read_only=True)
        active = wb.active
        isheet = file[0:-5]     # sheet name is filename without extension
        sheet = wb[isheet] # ws is now an Iterableworksheet
        for row in sheet.rows:
            num = 0
            # only read the first 5 cells in a row and only date, image name, birdname
            # are used
            for cell in row:
                if num == 1 or num == 2:      # don't need priority, or breeding
                    num += 1
                    continue
                elif num == 0:    # int date, make it a string
                    date = str(cell.value)
                    date = date[0:6]            # only year and month
                elif num == 3:                  # get image name
                    image = cell.value
                elif num == 4:                  # get bird name
                    birdname = cell.value
                num += 1
                if num > 5: break               # done processing row
            #pdb.set_trace()
            key = date + ":" + image
            if key in dbs:
                print ("Shouldn't have duplicate date/image name in databases", date, image)
            dbs[key] = birdname

# main routine
dir = "../2*"
garbage = "../garbage"
dbs = {}

    # read in the databases so I can figure out which bird wants to be deleted
read_excel(dbs)

while 1:
    ans = input("file to delete: ")
    ans = ans.rstrip('\n')
    if ans == 'q' or len(ans) < 1:
        break
    name = '*' + ans + '*'
    array = findit (dir, name)
    if len(array)==1 and not array[0]:
        print ("file not found, try again")
        continue
            # now create a dictionary of the files found, where the unique
            # dict element is based on the date and name found.
            # in other words, I am putting all files together that go together
    ffiles = {}
    for line in array:
        if len(line) < 1: continue  # get rid of that ending blank line
        fields = line.split('/')
                # get year and month for date
        date = fields[1] + fields[2]
                # get rid of the ending extension on the filename, if there is one
        if '.' in fields[-1]:
            end = fields[-1].rfind(".")
            image = fields[-1][0:end]
        else:
            image = fields[-1]
                # key is date and image name
        pointer = date + ":" + image
        if not pointer in ffiles:
            ffiles[pointer] = []
        ffiles[pointer].append(line)

            # now cycle through the found items by date and see if that is the one to be
            # deleted.
    keys = list(ffiles.keys())
    print ('Possible number of files to remove: ', len(keys))
    for key in keys:
        date, image = key.split(':')
        if key in dbs:
            bird = dbs[key]
        else:
            bird = 'unknown'
        fnum = len(ffiles[key])
        ttext = 'Delete ' + str(fnum) + ' files for '+ bird+ ': '+ date+ '--'+ image+ ": "
        ans = input(ttext)
        if ans == "y" or ans == "Y":
            for kk in ffiles[key]:
                    # delete all files except ones in Full_res, move those to my 'garbage'
                print ('mv to trash: ', kk)
                send2trash.send2trash(kk)
            break
