import os, datetime, hashlib
import jwt, bcrypt
from bson.objectid import ObjectId
from flask import request, jsonify, Response
from util import database, mail

secret = os.environ.get('JWT_PASSWORD_SECRET')

def create_reset_token():
  data = request.get_data()
  if not data: return jsonify({'success': False, 'message': 'Invalid request'}), 400
  db = database.get_db()
  user = db.users.find_one({'email': data.decode('ascii')})
  if not user: return jsonify({'success': True})
  now = datetime.datetime.utcnow()
  payload = {
    'iat': now,
    'exp': now + datetime.timedelta(hours = 3),
    'sub': str(user['_id'])
  }
  token = jwt.encode(payload, secret, algorithm='HS256').decode("utf-8")
  db.users.update_one({'_id': user['_id']}, {'$set': {'passwordResetToken': token}})
  try:
    mail.send(user['email'], 'Password reset', f'Hi there,\n\nTo reset your password please use the following token when prompted by the dotty client:\n\n{token}\n\nThanks,\n\nDotty', 'Dotty Accounts <accounts@mail.dotty.cloud>')
    return jsonify({'success': True})
  except Exception as e:
    print(e)
    return jsonify({'success': False, 'message': 'We were unable to send a password-reset email. Please try again later.'}), 500

def update(data):
  print(data)
  if not data:
    return jsonify({'success': False, 'message': 'Invalid request'}), 400
  password = data.get('password')
  token = data.get('token')
  if not password or not token: return jsonify({'success': False, 'message': 'Invalid request'}), 400

  db = database.get_db()
  user = None
  try:
    user_id = jwt.decode(token, secret)['sub']
    user = db.users.find_one({'_id': ObjectId(user_id)})
    if not user: raise Exception
  except Exception as e:
    print(e)
    return jsonify({'success': False, 'message': 'Unable to update password. Your token may be invalid'}), 400
  hashed_password = bcrypt.hashpw(hashlib.sha256(password.encode('utf-8')).hexdigest().encode('utf-8'), bcrypt.gensalt())
  db.users.update_one({'_id': user['_id']}, {'$set': {'password': hashed_password.decode('utf-8')}})
  return jsonify({'success': True})
