<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def update_user_stats(self, username, task, submission, result_str, grade, state, newsub):
 """ Update stats with a new submission """

        self.user_saw_task(username, submission["courseid"], submission["taskid"])

        if newsub:
            old_submission = self._database.user_tasks.find_one_and_update(
                {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$inc": {"tried": 1, "tokens.amount": 1}})

            # Check if the submission is the default download
            set_default = task.get_evaluate() == 'last' or \
                          (task.get_evaluate() == 'student' and old_submission is None) or \
                          (task.get_evaluate() == 'best' and old_submission.get('grade', 0.0) <= grade)

            if set_default:
                self._database.user_tasks.find_one_and_update(
                    {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
                    {"$set": {"succeeded": result_str == "success", "grade": grade, "state": state, "submissionid": submission['_id']}})
        else:
            old_submission = self._database.user_tasks.find_one(
                {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]})

            if task.get_evaluate() == 'best':  # if best, update cache consequently (with best submission)
                def_sub = list(self._database.submissions.find({
                    "username": username, "courseid": task.get_course_id(),
                    "taskid": task.get_id(), "status": "done"}
                ).sort([("grade", pymongo.DESCENDING), ("submitted_on", pymongo.DESCENDING)]).limit(1))

                if len(def_sub) > 0:
                    self._database.user_tasks.find_one_and_update(
                        {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
                        {"$set": {
                            "succeeded": def_sub[0]["result"] == "success",
                            "grade": def_sub[0]["grade"],
                            "state": def_sub[0]["state"],
                            "submissionid": def_sub[0]['_id']
                        }})
            elif old_submission["submissionid"] == submission["_id"]:  # otherwise, update cache if needed
                self._database.user_tasks.find_one_and_update(
                    {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]},
                    {"$set": {
                        "succeeded": submission["result"] == "success",
                        "grade": submission["grade"],
                        "state": submission["state"]
                    }})