import json
from .tag_weapon_list import weapons
from .stickers_list import stickers
import re
from app.models import cs2snipe_queries
from app.models import cs2snipe_found
from app.models import cs2snipe_users
from datetime import datetime
from django.utils import timezone
from .pikahandler import sendQuery

#{'weapon_name': 'tag_weapon_knife_flip', 'skin_or_weapon': 'weapon', 'stat': 'stat_only', 'filter_options': 'other_filter', 'condition': 'Factory New', 'more_filters': ['rank'], 'rank': 1, 'pages': 2, 'question1': ['Item 1']}
#{'weapon_name': 'tag_weapon_ak47', 'skin_or_weapon': 'weapon', 'stat': 'stat_and_non_stat', 'filter_options': 'exact_float', 'exact_float': 0.499945, 'more_filters': ['rank', 'pattern', 'price'], 'rank': 1, 'pattern': 2, 'price': 3, 'pages': 4, 'question1': ['Item 1']}

#{'weapon_name': 'tag_weapon_famas', 'skin_or_weapon': 'weapon', 'stat': 'stat_only', 'filter_options': 'float_restrictions', 'float_restrictions': 'starts_with', 'float_for_restriction': 0.1, 'more_filters': ['rank'], 'rank': 1, 'pages': 1, 'question1': ['Item 1']}
#{'weapon_name': 'tag_weapon_knife_flip', 'skin_or_weapon': 'weapon', 'stat': 'stat_and_non_stat', 'filter_options': 'float_restrictions', 'float_restrictions': 'is_bigger', 'float_for_restriction': 0.1, 'more_filters': ['price'], 'price': 1, 'pages': 1, 'question1': ['Item 1']}
#{'weapon_name': 'tag_weapon_knife_falchion', 'skin_or_weapon': 'weapon', 'stat': 'stat_and_non_stat', 'filter_options': 'float_restrictions', 'float_restrictions': 'is_smaller', 'float_for_restriction': 0.1, 'more_filters': ['rank'], 'rank': 1, 'pages': 2, 'question1': ['Item 1']}

#{'weapon_name': 'tag_weapon_galilar', 'skin_or_weapon': 'weapon', 'stat': 'stat_only', 'filter_options': 'other_filter', 'more_filters': ['rank', 'pattern', 'price'], 'condition': 'Battle-Scarred', 'rank': 1, 'pattern': 2, 'price': 3, 'pages': 1, 'question1': ['Item 1']}

#{'skin_or_weapon': 'skin', 'stat': 'stat_only', 'skin_name': 'AK-47 | Nighwish', 'filter_options': 'other_filter', 'condition': 'Factory New', 'more_filters': ['rank'], 'rank': 1, 'pages': 2, 'question1': ['Item 1']}


def validateBody(body, steamid):
    print(body)
    body = StrToFloat(result_json=body)
    if body[0] is not False:
        ret_val = None
        result_json = body[1]
        json_validated = checkJSON(result_json=result_json)
        
        if json_validated[1] == "All good":
            print("GEIL")
            new_query = cs2snipe_queries(
                steamid=steamid,
                query_json=result_json,
                query_failed=False,
                query_status="Working...",
                message="",
                pub_date=datetime.now(tz=timezone.get_default_timezone()),
            )
            ret_val = True
        else:
            print("FIX NED")
            new_query = cs2snipe_queries(
                steamid=steamid,
                query_json=result_json,
                query_failed=True,
                query_status="Failed",
                message=str(json_validated[1]),
                pub_date=datetime.now(tz=timezone.get_default_timezone()),
            )
            ret_val = False
        new_query.save(force_insert=True)
        
        if json_validated[1] == "All good":
            sendQuery(result_json=result_json, steamid=steamid, new_query=new_query)
        return ret_val
    else:
        return False

def StrToFloat(result_json):
    if result_json["filter_options"] == "exact_float":
        if "exact_float" in result_json:
            try:
                float(result_json["exact_float"])
            except ValueError:
                return False, result_json
            result_json["exact_float"] = float(result_json["exact_float"])

    if result_json["filter_options"] == "float_restrictions":
        if "float_restrictions" in result_json:
            if "float_for_restriction" in result_json:
                try:
                    float(result_json["float_for_restriction"])
                except ValueError:
                    return False, result_json
                result_json["float_for_restriction"] = float(result_json["float_for_restriction"])
    
    # if "price" not in result_json:
    #     result_json["price"] = 6969
    
    return True, result_json

def checkRequiredParams(result_json):
    if "skin_or_weapon" not in result_json:
        return False, "Skin or Weapon field missing."
    if result_json["skin_or_weapon"] != "weapon" and result_json["skin_or_weapon"] != "skin":
        return False, "Skin or Weapon field has a wrong value."

    if "weapon_name" not in result_json and "skin_name" not in result_json:
        return False, "No Weapon name or Skin name given."
    if "weapon_name" in result_json:
        if result_json["weapon_name"] not in weapons:
            return False, "Weapon doesn't exist."
    #SKIN NAME REGEX?
    if "skin_name" in result_json:
        pattern = re.compile(".+ \\| .+")
        matched = pattern.match(result_json["skin_name"])
        if matched is None:
            return False, "Skin name pattern doesn't match - it has to be like this: Weapon name | Skin name"
        
        #if result_json["weapon_name"] not in weapons:
        #    return False, "Weapon doesn't exist."

    if "type" not in result_json:
        return False, "Type value missing."
    if result_json["type"] != "stat_and_non_stat" and result_json["type"] != "stat_only" and result_json["type"] != "non_stat_only" and result_json["type"] != "all" and result_json["type"] != "souvenir":
        return False, "Type field has a wrong value."

    if "filter_options" not in result_json:
        return False, "No filter options selected."
    if result_json["filter_options"] != "other_filter" and result_json["filter_options"] != "exact_float" and result_json["filter_options"] != "float_restrictions":
        return False, "Filter options has wrong value."
    
    if result_json["filter_options"] == "exact_float":
        if "exact_float" not in result_json:
            return False, "Exact float value missing."
        try:
            float(result_json["exact_float"])
        except ValueError:
            return False, "Exact float value isn't a float."
        result_json["exact_float"] = float(result_json["exact_float"])
        #if isinstance(result_json["exact_float"], float) is False:
        #    return False, "Exact float value isn't a float."
        if result_json["exact_float"] >= 1:
            return False, "Exact float value is bigger than 1."
    #'more_filters': ['rank', 'pattern', 'price'], 'condition': 'Battle-Scarred', 'rank': 1, 'pattern': 2, 'price': 3,
    if result_json["filter_options"] == "other_filter":
        # if "condition" not in result_json:
        #     if "condition_wep" not in result_json:
        #         return False, "Condition missing."
        # if len(result_json["condition"]) == 0:
        #     return False, "Condition not selected."
        if "more_filters" not in result_json:
            return False, "No other filters selected."
        else:
            if "rank" in result_json["more_filters"]:
                # if result_json["rank"] > 5:
                #     return False, "Rank can't be greater than 5."
                # if result_json["maxfloatrank"] == "top5":
                #     if result_json["rank"] > 5:
                #         return False, "Rank can't be greater than 5."
                if "csfloat_rank" in result_json:
                    if result_json["csfloat_rank"] > 1000:
                        return False, "csfloat rank can't be greater than 1000."
                    if result_json["csfloat_rank"] < 0:
                        return False, "csfloat rank can't be negative."
            if "pattern" in result_json["more_filters"]:
                if result_json["pattern"] > 1000:
                    return False, "Pattern index can't be greater than 1000."
            if "price" in result_json["more_filters"]:
                if result_json["price"] != 6969:
                    if result_json["price"] > 2000:
                        return False, "Price can't be greater than 2000."
                #{'stickerpanel': [{'sticker': 'Shooter Close'}, {'sticker': 'Polar Bears'}, {'sticker': 'Lucky 13'}, {'sticker': 'Team LDLC.com (Holo) | Katowice 2014'}], 'skin_or_weapon': 'skin', 'type': 'stat_only', 'skin_name': 'Desert Eagle | Heirloom', 'filter_options': 'other_filter', 'condition': 'Battle-Scarred', 'more_filters': ['stickers'], 'pages': 1, 'question1': ['Item 1']}
            if "stickers" in result_json["more_filters"]:
                if "stickerpanel" not in result_json:
                    return False, "Sitckerpanel not found."
                stickerpanel = result_json["stickerpanel"]
                for sticker in stickerpanel:
                    if "sticker" not in sticker:
                        return False, "Bruh"
                    if sticker["sticker"] not in stickers:
                        return False, "The sticker " + str(sticker["sticker"]) + " doesnt exist?"
        
    if result_json["filter_options"] == "float_restrictions":
        if "float_restrictions" not in result_json:
            return False, "Float restrictions field missing."
        if "float_for_restriction" not in result_json:
            return False, "Float for restriction field missing."
        if result_json["float_restrictions"] != "starts_with" and result_json["float_restrictions"] != "is_bigger" and result_json["float_restrictions"] != "is_smaller":
            return False, "Float restrictions field has a wrong value."
        try:
            float(result_json["float_for_restriction"])
        except ValueError:
            return False, "Float for restriction is not a float."
        result_json["float_for_restriction"] = float(result_json["float_for_restriction"])

        if result_json["float_for_restriction"] >= 1:
            return False, "Float for restrictions is bigger than 1."
    
    if "pages" not in result_json:
        return False, "Amount of market pages missing."
    if result_json["skin_or_weapon"] == "weapon" and result_json["pages"] > 10:
        return False, "Amount of market pages can't be greater than 10 for weapons."
    if result_json["skin_or_weapon"] == "skin" and result_json["pages"] > 20:
        return False, "Amount of market pages can't be greater than 20 for skins."

    return True, "All good"

def checkJSON(result_json):
    try:
        ret = checkRequiredParams(result_json=result_json)
    except Exception as e:
        print(str(e))
        return False
    # print(ret)
    if ret[0] is False:
        return False, ret[1]
    else:
        return True, "All good"
