#!/usr/bin/python3
import sys

import utils
from object_store_abstraction import TryingToCreateExistingObjectExceptionClass


commands = []

print("Start of " + sys.argv[0])


def listPossibleStores():
  for x in utils.configs:
    print(x["shortName"] + " (" + x["abspath"]  + ")")
  print("Done")

commands.append({
  'Name': 'List Possible Stores',
  'fn': listPossibleStores
})

def writeLines():
  store = utils.getAnObjectStoreFromUser("Select object store to use")
  dataSet = utils.getADataset("Select dataset to test")

  objectType = "lines"
  i = input("Enter objectType to use or blank for 'lines':")
  if i != "":
    objectType = i

  def dbfn(storeConnection):
    lineNum = 0
    for x in dataSet:
      lineNum = lineNum + 1
      print("Writing ", x)
      try:
        key = "L:" + str(x).strip()
        storeConnection.saveJSONObject(objectType, key, {'key':key, 'data': x})
      except TryingToCreateExistingObjectExceptionClass:
        print("  Skipping - already exists")
  a = store.executeInsideTransaction(dbfn)

  print("Done writing now reading...")

  def dbfn2(storeConnection):
    return storeConnection.getAllRowsForObjectType(objectType, filterFN=None, outputFN=None, whereClauseText=None)
  lis = store.executeInsideTransaction(dbfn2)
  for x in lis:
    print(x)

  print("Done")

commands.append({
  'Name': 'Write text file and read back',
  'fn': writeLines
})

def readLines():
  store = utils.getAnObjectStoreFromUser("Select object store to use")

  def dbfn2(storeConnection):
    return storeConnection.list_all_objectTypes()
  objectTypeList = store.executeInsideTransaction(dbfn2)

  if len(objectTypeList) == 0:
    print("No data in this store")
    return
  res = utils.userSelectOptionFromList("Which object type for you want to read?", objectTypeList, None)

  objectType = objectTypeList[res]

  print("Reading lines...")


  def dbfn2(storeConnection):
    return storeConnection.getAllRowsForObjectType(objectType, filterFN=None, outputFN=None, whereClauseText=None)
  lis = store.executeInsideTransaction(dbfn2)
  for x in lis:
    print(x)

  print("Done")

commands.append({
  'Name': 'Read data fro mstore',
  'fn': readLines
})

def deleteLines():
  store = utils.getAnObjectStoreFromUser("Select object store to use")

  print("Deleting lines...")

  def dbfn2(storeConnection):
    return storeConnection.list_all_objectTypes()
  objectTypeList = store.executeInsideTransaction(dbfn2)

  if len(objectTypeList) == 0:
    print("No data in this store")
    return
  res = utils.userSelectOptionFromList("Which object type for you want to delete?", objectTypeList, None)

  objectType = objectTypeList[res]


  def dbfn2(storeConnection):
    lins = storeConnection.getAllRowsForObjectType(objectType, filterFN=None, outputFN=None, whereClauseText=None)
    for objectDICT, ObjectVersion, creationDate, lastUpdateDate, objectKey in lins:
      storeConnection.removeJSONObject(objectType, objectKey)
  lis = store.executeInsideTransaction(dbfn2)

  print("Done")

commands.append({
  'Name': 'Delete lines',
  'fn': deleteLines
})

def showInfo():
  store = utils.getAnObjectStoreFromUser("Select object store to use")

  def dbfn2(storeConnection):
    objectTypes = storeConnection.list_all_objectTypes()
    print("ObjectType NumRows")
    for objectType in objectTypes:
      allKeys = storeConnection.getAllRowsForObjectType(
        objectType=objectType,
        filterFN=None,
        outputFN=utils.outputFnJustKeys,
        whereClauseText=None
      )
      print((objectType + utils.space)[:30] + " " + str(len(allKeys)))
    print("\n")
    print("Total Object Types:", len(objectTypes))
  store.executeInsideTransaction(dbfn2)


commands.append({
  'Name': 'Show info about data in a store',
  'fn': showInfo
})

running = { 'val': True }

from cmdCompareTwoStores import getCommand as compareTwoStores_getCommand
commands.append(compareTwoStores_getCommand())
from cmdCaculateMigrationPercentage import getCommand as cmdCaculateMigrationPercentage_getCommand
commands.append(cmdCaculateMigrationPercentage_getCommand())
from cmdPreformMigration import getCommand as cmdPreformMigration_getCommand
commands.append(cmdPreformMigration_getCommand())



while running['val']:
  selectedCommand = utils.userSelectOptionFromList("Select command to run (q to quit):", commands, "Name")
  commands[selectedCommand]["fn"]()


print("End of " + sys.argv[0])
exit(0)
