# AUTOGENERATED! DO NOT EDIT! File to edit: database.ipynb (unless otherwise specified).

__all__ = ['NeedUpdateIndex', 'Database', 'lambdaDumpToS3', 'lambdaSplitBranch', 'lambdaSaveS3', 'lambdaSingleQuery',
           'lambdaBranchUrl', 'lambdaAllQuery']

# Cell
from villaInvDatabase.helper import DatabaseHelper
from villaInvDatabase.s3 import DatabaseS3
from villaInvDatabase.query import Querier
from villaInvDatabase.update import Updater
import pandas as pd
from datetime import datetime
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, NumberAttribute, JSONAttribute, BooleanAttribute, BinaryAttribute
from pynamodb.indexes import GlobalSecondaryIndex, AllProjection
from awsSchema.apigateway import Response, Event
from botocore.config import Config
from s3bz.s3bz import S3
from linesdk.slack import SlackBot
from pprint import pprint

import pickle, json, boto3, bz2, requests, validators, os, logging

# Cell
try:
  SLACK = os.environ.get('SLACK')
  DATABASE_TABLE_NAME = os.environ['DATABASE_TABLE_NAME']
  INVENTORY_BUCKET_NAME = os.environ['INVENTORY_BUCKET_NAME']
  INPUT_BUCKET_NAME = os.environ['INPUT_BUCKET_NAME']
  REGION = os.environ['REGION']
  ACCESS_KEY_ID = None
  SECRET_ACCESS_KEY = None
except Exception as e:
  print(f'error, missing environment variables \n{e}')
  DATABASE_TABLE_NAME = None
  INVENTORY_BUCKET_NAME = None
  INPUT_BUCKET_NAME = None
  ACCESS_KEY_ID = None
  SECRET_ACCESS_KEY = None
  REGION = 'ap-southeast-1'
try:
  DAX_ENDPOINT = os.environ['DAX_ENDPOINT']
except:
  DAX_ENDPOINT = None
  print('dax endpoint missing')


# Cell
class NeedUpdateIndex(GlobalSecondaryIndex):
  class Meta:
    index_name = 'need-update'
    projection = AllProjection()
    read_capacity_units = 1
    write_capacity_units = 1
  needUpdate = UnicodeAttribute(default=False, hash_key=True)

# Cell
# dont forget to import dependent classes from the relevant notebooks
class Database(Model, DatabaseS3, Updater, Querier, DatabaseHelper):
  class Meta:
    aws_access_key_id = ACCESS_KEY_ID
    aws_secret_access_key = SECRET_ACCESS_KEY
    table_name = DATABASE_TABLE_NAME
    region = REGION
    billing_mode='PAY_PER_REQUEST'
    dax_read_endpoints = [DAX_ENDPOINT] if DAX_ENDPOINT else None
    dax_write_endpoints = [DAX_ENDPOINT] if DAX_ENDPOINT else None

  ib_prcode = UnicodeAttribute(hash_key=True, default = '')
  lastUpdate = NumberAttribute( default = 0)
  inventory = JSONAttribute(default={})
  needUpdate = UnicodeAttribute(default= 'N')
  needUpdateIndex = NeedUpdateIndex()
  TRUE = 'Y'
  FALSE = 'N'

  def __repr__(self):
    invDict = self.inventory
    invDict['ib_prcode'] = self.ib_prcode
    return json.dumps(invDict)
  def setNoUpdate(self, batch = None):
    self.needUpdate = self.FALSE
    if batch:
      return batch.save(self)
    else:
      return self.save()
  def setUpdate(self):
    self.needUpdate = self.TRUE
    return self.save()

# Cell
def lambdaDumpToS3(event, _):
  result = Database.dumpToS3()
  try:
    bot = SlackBot(SLACK)
    bot.sendMessage(f'{result}')
  except:
    logging.exception('unable to send slack')
  return Response.getReturn(body={'savingResult': result})

# Cell
def lambdaSplitBranch(event, _):
  result = Database.splitBranches(bucket = INVENTORY_BUCKET_NAME)
  try:
    bot = SlackBot(SLACK)
    bot.sendMessage(f'{result}')
  except:
    logging.exception('unable to send slack')
  return Response.getReturn(body={'savingResult': result})

# Cell
def lambdaSaveS3(events, _):
  key = events.get('key')
  updateResult = Database.updateS3Input(
    inputBucketName=INPUT_BUCKET_NAME, key= key)
  return Response.getReturn(body = {'saveResult': updateResult})

# Cell
def lambdaSingleQuery(event, _):
  body = Event.from_dict(event).getBody()
  result = Database.singleProductQuery(body).inventory
  return Response.getReturn(body = result)


# Cell
def lambdaBranchUrl (events, _):
  if 'body' not in events.keys(): return Response.getReturn(statusCode=400, body = {'error': 'missing body tag'})
  branch = Event.from_dict(events).getBody()['branch']
  branchURL = Database.branchQuery('1000', bucket = INVENTORY_BUCKET_NAME)
  print(branchURL[:20])
  return Response.getReturn(body = {'url': branchURL})

# Cell
def lambdaAllQuery (events, _):
  url = Database.allQuery(bucket = INVENTORY_BUCKET_NAME, user=USER, pw=PW)
  print(url[:20])
  return Response.getReturn(body = {'url': url})
