from productivity_bot.models import User, ActiveLoops, UserResponses
from productivity_bot.api_helper import APIHelper

COMMAND_ERROR = 'Sorry, that was an invalid command.'
SESSION_BEGIN = 'Working session has begun! To end the session, say "stop"'
SESSION_END = 'Working session has ended! See a summary of your work here: %s'

def handle_inbound_message(message_text, user_id, space_name, email):
  user = User.objects.get_or_create(
    space_name=space_name,
    user_id=user_id,
    email=email
  )[0]

  message = message_text.lower().split()
  if message[0] == 'start':
    if (len(message) != 1 or get_active_loop(user)):
      return COMMAND_ERROR

    return start_active_loop(user)
  if message[0] == 'stop':
    if len(message) != 1 or not get_active_loop(user):
      return COMMAND_ERROR

    return end_active_loop(user)
  if not get_active_loop(user):
    return COMMAND_ERROR

  return log_user_response(user, message)


def start_active_loop(user):
  active_loop = get_active_loop(user)
  if active_loop:
    active_loop.delete()

  ActiveLoops(user=user).save()

  return SESSION_BEGIN


def end_active_loop(user):
  active_loop = get_active_loop(user)
  if not active_loop:
    return "You are not in a working session."

  api_helper = APIHelper('service_account.json')

  sheet_properties, file_existed = api_helper.get_or_create_sheet(user)
  sheet_id = sheet_properties['sheetId']
  spreadsheet_id = user.spreadsheet_id

  # If the file was just created, share it with the user
  if not file_existed:
    api_helper.share_drive_file(spreadsheet_id, user.email)

  # Copy the information from the UserResponses table to this sheet
  api_helper.copy_sql_table_to_sheet(
    UserResponses,
    {'active_loop': active_loop},
    spreadsheet_id,
    sheet_properties['title']
  )

  active_loop.delete()
  sheet_link = 'https://docs.google.com/spreadsheets/d/{}#gid={}'.format(
    spreadsheet_id, sheet_id)
  return SESSION_END% sheet_link


def get_active_loop(user):
  active_loop = ActiveLoops.objects.filter(user=user)
  if active_loop.exists():
    return active_loop[0]
  return None


def log_user_response(user, text):
  active_loop = ActiveLoops.objects.get(user=user)
  raw_text = " ".join(text)

  user_response = UserResponses(active_loop=active_loop, raw_text=raw_text)
  user_response.save()

  return "Response has been logged!"
