"""
    Copyright (c) 2015-2020 Raj Patel(raj454raj@gmail.com), StopStalk

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
"""

import datetime
import json
import time

import parsedatetime as pdt
import requests
import utilities


# ------------------------------------------------------------------------------
def status_check():
    return "up and running..."

# ----------------------------------------------------------------------------
def handle_error():
    """
        Handles errors and shows valid error messages
        Also notifies the admin by an email
    """

    def _get_similar_users(url):

        from difflib import SequenceMatcher
        handle = (url.replace("users", "")
                     .replace("user", "")
                     .replace("profiles", "")
                     .replace("profile", "")
                     .replace("submissions", "")
                     .replace("submission", "")
                     .replace("/", "")
                     .lower())
        atable = db.auth_user
        cftable = db.custom_friend
        prospects = []
        users = db(atable).select(atable.first_name,
                                  atable.last_name,
                                  atable.stopstalk_handle).as_list()
        custom_users = db(cftable).select(cftable.first_name,
                                          cftable.last_name,
                                          cftable.stopstalk_handle).as_list()

        prospects.extend([(x["first_name"],
                           x["last_name"],
                           x["stopstalk_handle"]) for x in users + \
                                                           custom_users])

        similar_users = []
        for prospect in prospects:
            fname, lname, stopstalk_handle = prospect
            diff1 = SequenceMatcher(None, fname.lower(), handle).ratio()
            diff2 = SequenceMatcher(None, lname.lower(), handle).ratio()
            diff3 = SequenceMatcher(None,
                                    stopstalk_handle.lower(),
                                    handle).ratio()
            diff = max(diff1, diff2, diff3)
            if diff >= 0.8:
                similar_users.append(({"stopstalk_handle": stopstalk_handle,
                                       "name": fname + " " + lname},
                                      diff))

        similar_users.sort(key=lambda x: x[1], reverse=True)

        return [x[0] for x in similar_users[:10]]

    def _get_failure_message(ticket):

        from os import path
        from pickle import load

        from gluon.admin import apath

        failure_message = str(session.user_id) + " " if auth.is_logged_in() else ""
        ticket_file_path = "applications/stopstalk/errors/" + \
                           ticket.replace(request.application + "/", "")

        if path.exists(ticket_file_path):
            failure_message += load(open(ticket_file_path, "rb"))["output"]
        else:
            failure_message += "Shouldn't be here"

        return "<html>" + str(A(failure_message,
                                _href=URL("admin", "default", "ticket",
                                          args=ticket,
                                          scheme=True,
                                          host=True))) + "</html>"

    code = request.vars.code
    request_url = request.vars.request_url
    ticket = request.vars.ticket

    # Make sure error url is not current url to avoid infinite loop.
    if code is not None and request_url != request.url:
        # Assign the error status code to the current response
        response.status = int(code)

    error_message = ""
    similar_users = []
    if code == "404":
        similar_users = _get_similar_users(request_url)
        message = request_url + \
                  " " + \
                  str([x["stopstalk_handle"] for x in similar_users])
        error_message = "Not found"
    elif code == "401":
        message = "Invalid token"
        error_message = "Invalid token"
    elif code == "500":
        # Get ticket URL:
        ticket_url = URL("admin", "default", "ticket",
                         args=ticket,
                         scheme=True,
                         host=True)
        message = (str(session.user_id) if auth.is_logged_in() else "") + " " + ticket_url
        error_message = "Internal Server error"
        current.send_mail("raj454raj@gmail.com",
                          "500 occurred",
                          _get_failure_message(ticket),
                          mail_type="admin")
    else:
        message = request.vars.requested_uri if request.vars.requested_uri else request_url
        error_message = "Other error"

    return dict(error_message=error_message, similar_users=similar_users)

# ----------------------------------------------------------------------------
@auth.requires_login()
def get_card_html():
    init_arguments = request.vars["init_arguments[]"]

    if not isinstance(init_arguments, list):
        init_arguments = [init_arguments]

    if int(init_arguments[0]) != session.user_id:
        return ""

    import dashboard_cards
    card_class = getattr(dashboard_cards,
                         request.vars["class_name"])(*init_arguments)

    return card_class.get_html() if card_class.should_show() else ""

# ----------------------------------------------------------------------------
def support_us():
    return dict()

# ----------------------------------------------------------------------------
@auth.requires_login()
def dashboard():
    session.welcome_shown = True
    ratable = db.recent_announcements
    rarecord = db(ratable.user_id == session.user_id).select().first()
    if rarecord is None:
        ratable.insert(user_id=session.user_id)
        rarecord = db(ratable.user_id == session.user_id).select().first()

    user = session.auth.user
    db.sessions_today.insert(message="%s %s %d %s" % (user.first_name,
                                                      user.last_name,
                                                      user.id,
                                                      datetime.datetime.now()))

    return dict(recent_announcements=json.loads(rarecord.data))

# ----------------------------------------------------------------------------
@auth.requires_login()
def cta_handler():
    problem_id = utilities.pick_a_problem(
                    session.user_id,
                    False,
                    **request.vars
                )
    redirect(URL("problems",
                 "index",
                 vars=dict(problem_id=problem_id,
                           submission_type="global")))

# ----------------------------------------------------------------------------
def user_editorials():