import pandas as pd
import requests
from datetime import datetime
import numpy as np

tags_list = ['Indie',
             'Low Confidence Metric',
             'Action',
             'Casual',
             'Adventure',
             'Singleplayer',
             'Simulation',
             'Strategy',
             'RPG',
             '2D',
             'Atmospheric',
             'Puzzle',
             'Free to Play',
             'Early Access',
             'Story Rich',
             'Multiplayer',
             'Pixel Graphics',
             'Fantasy',
             '3D',
             'Colorful',
             'Anime',
             'First-Person',
             'Violent',
             'Cute',
             'Exploration',
             'Arcade',
             'Nudity',
             'Funny',
             'Sexual Content',
             'Sci-fi',
             'Shooter',
             'VR',
             'Platformer',
             'Horror',
             'Great Soundtrack',
             'Retro',
             'Gore',
             'Family Friendly',
             'Relaxing',
             'Difficult',
             'Sports',
             'Open World',
             'Female Protagonist',
             'Action-Adventure',
             'Survival',
             'Co-op',
             'Visual Novel',
             'Third Person',
             'Racing',
             'Comedy',
             'FPS',
             'Massively Multiplayer',
             'Stylized',
             'Realistic',
             'Old School',
             'Top-Down',
             'Sandbox',
             'Physics',
             'Turn-Based',
             'Online Co-Op',
             'PvP',
             "Shoot 'Em Up",
             'Choices Matter',
             'Mystery',
             'Point & Click',
             'Space',
             'Minimalist',
             'Cartoony',
             '2D Platformer',
             'Dark',
             'Psychological Horror',
             'Combat',
             'Management',
             'Adult Content',
             'Controller',
             'Building',
             'Side Scroller',
             'Multiple Endings',
             'Tactical',
             'Character Customization',
             'Local Multiplayer',
             'Puzzle-Platformer',
             'Replay Value',
             'Hand-drawn',
             'Design & Illustration',
             'Action RPG',
             'Linear',
             '1980s',
             'Turn-Based Strategy',
             'Education',
             'Magic',
             'Rogue-like',
             'Procedural Generation',
             'Futuristic',
             'Crafting',
             'PvE',
             'Survival Horror',
             'Party-Based RPG',
             'Local Co-Op',
             'Rogue-lite',
             'Mature',
             'Turn-Based Combat',
             'Logic',
             'Software',
             'Medieval',
             'Cartoon',
             'JRPG',
             'Zombies',
             'Hidden Object',
             '3D Platformer',
             'Utilities',
             'Historical',
             'War',
             'Romance',
             'Resource Management',
             'Hack and Slash',
             'Turn-Based Tactics',
             'Classic',
             'Choose Your Own Adventure',
             'Short',
             'Fast-Paced',
             'Bullet Hell',
             'Interactive Fiction',
             'Drama',
             'Walking Simulator',
             'Post-apocalyptic',
             'Movie',
             'Dark Fantasy',
             'Dungeon Crawler',
             'Web Publishing',
             'Stealth',
             'RPGMaker',
             'Surreal',
             'RTS',
             'Base Building',
             'Memes',
             'Top-Down Shooter',
             'Dating Sim',
             'Isometric',
             'Score Attack',
             'Experimental',
             'Military',
             "1990's",
             'Music',
             'Card Game',
             'Narration',
             'Cyberpunk',
             'Text-Based',
             'Third-Person Shooter',
             'Fighting',
             'Abstract',
             'Soundtrack',
             'Driving',
             'Hentai',
             '2.5D',
             'Emotional',
             'Robots',
             'Immersive Sim',
             'Action Roguelike',
             'Board Game',
             '4 Player Local',
             'Flight',
             'Tower Defense',
             'Nature',
             'Economy',
             'LGBTQ+',
             'Aliens',
             'Dark Humor',
             'Competitive',
             'Detective',
             'Investigation',
             'Perma Death',
             'Tabletop',
             'City Builder',
             'Beautiful',
             'Team-Based',
             'Clicker',
             'Arena Shooter',
             'Cinematic',
             'Precision Platformer',
             'Metroidvania',
             'Time Management',
             'Real Time Tactics',
             'NSFW',
             "Beat 'em up",
             'Strategy RPG',
             'Life Sim',
             'Conversation',
             'Thriller',
             'Wargame',
             'Moddable',
             'Psychological',
             'Psychedelic',
             'Tactical RPG',
             'Tutorial',
             'Demons',
             'Animation & Modeling',
             'Level Editor',
             'Character Action Game',
             'Automobile Sim',
             'Destruction',
             'Nonlinear',
             'Twin Stick Shooter',
             'Modern',
             'Dystopian',
             'Runner',
             'Comic Book',
             'World War II',
             'Alternate History',
             'Lore-Rich',
             'Crime',
             '2D Fighter',
             'Rhythm',
             'Audio Production',
             'Loot',
             'Parkour',
             'Grand Strategy',
             'Artificial Intelligence',
             'Game Development',
             'Supernatural',
             'Souls-like',
             'Match 3',
             'Inventory Management',
             'Space Sim',
             'Grid-Based Movement',
             'MMORPG',
             'CRPG',
             'Science',
             'Dark Comedy',
             'Mythology',
             'Philosophical',
             'Lovecraftian',
             'Open World Survival Craft',
             'Collectathon',
             'Split Screen',
             'Video Production',
             'Mouse only',
             'Cats',
             'Addictive',
             'Card Battler',
             'Deckbuilding',
             'Noir',
             'Episodic',
             'Idler',
             'Software Training',
             'Swordplay',
             'Battle Royale',
             'eSports',
             'Voxel',
             'Dragons',
             'Real-Time',
             'Blood',
             '6DOF',
             'Steampunk',
             'Mechs',
             'Colony Sim',
             '3D Fighter',
             'Vehicular Combat',
             'Tanks',
             'Parody',
             'Political',
             'Bullet Time',
             'Class-Based',
             'Farming Sim',
             'Time Manipulation',
             '3D Vision',
             '4X',
             'Pirates',
             'Word Game',
             'Cult Classic',
             'Co-op Campaign',
             'Mystery Dungeon',
             'Hex Grid',
             'Capitalism',
             'Solitaire',
             'Gun Customization',
             'America',
             'Ninja',
             'Satire',
             'Trains',
             'Gothic',
             'Trading',
             'Hero Shooter',
             'Hunting',
             'Hacking',
             'Agriculture',
             'FMV',
             'Otome',
             'Time Travel',
             'Photo Editing',
             'Real-Time with Pause',
             'Combat Racing',
             'God Game',
             'Conspiracy',
             'Automation',
             'Remake',
             'Naval',
             'Mining',
             'Martial Arts',
             'Western',
             'Dinosaurs',
             'Spectacle fighter',
             'Sokoban',
             'Underwater',
             'MOBA',
             'Underground',
             'Politics',
             'Programming',
             'Dog',
             'Dungeons & Dragons',
             'Creature Collector',
             'Trading Card Game',
             'Touch-Friendly',
             'Fishing',
             'Illuminati',
             'Superhero',
             'GameMaker',
             'Vampire',
             'Cold War',
             'Political Sim',
             'Looter Shooter',
             'Dynamic Narration',
             'Kickstarter',
             'Faith',
             'Minigames',
             'Quick-Time Events',
             'Assassin',
             'Experience',
             'Documentary',
             'Asynchronous Multiplayer',
             'Naval Combat',
             'Music-Based Procedural Generation',
             'Soccer',
             'Party Game',
             'Narrative',
             'Time Attack',
             'Archery',
             'Auto Battler',
             'Heist',
             'Typing',
             'On-Rails Shooter',
             'Football',
             'Transportation',
             'Party',
             'Diplomacy',
             'Immersive',
             'Sailing',
             'Cooking',
             'Villain Protagonist',
             'Mod',
             'Chess',
             'Trivia',
             'Snow',
             'Offroad',
             'Epic',
             'Foreign',
             'Mars',
             'TrackIR',
             'Sequel',
             'Horses',
             '360 Video',
             'Sniper',
             'World War I',
             'Gambling',
             'Crowdfunded',
             'Boxing',
             'Gaming',
             'LEGO',
             'Silent Protagonist',
             'Traditional Roguelike',
             'Roguelike Deckbuilder',
             'Pinball',
             'Werewolves',
             'Based On A Novel',
             'Unforgiving',
             'Games Workshop',
             'Transhumanism',
             'Rome',
             'Action RTS',
             'Warhammer 40K',
             'Nostalgia',
             'Golf',
             'Medical Sim',
             'Motorbike',
             'Electronic Music',
             'Ambient',
             'Farming',
             'Jet',
             'Outbreak Sim',
             'Spelling',
             'Bikes',
             'Submarine',
             'Basketball',
             'Asymmetric VR',
             'Social Deduction',
             'Roguevania',
             'Mini Golf',
             'Spaceships',
             'Escape Room',
             'Intentionally Awkward Controls',
             'Wrestling',
             'Lemmings',
             'Instrumental Music',
             'Pool',
             'Baseball',
             'Tennis',
             'Hockey',
             'Skateboarding',
             'Vikings',
             'Motocross',
             'Feature Film',
             'Skating',
             'Electronic',
             'Cycling',
             'Bowling',
             'Rock Music',
             'Voice Control',
             'Benchmark',
             'ATV',
             'Skiing',
             'Snowboarding',
             'Well-Written',
             'Hardware',
             '8-bit Music',
             'BMX',
             'Steam Machine',
             'Reboot']
lang_list = ['Arabic',
             'Bulgarian',
             'Chinese (Simplified)',
             'Chinese (Traditional)',
             'Czech',
             'Danish',
             'Dutch',
             'English',
             'Finnish',
             'French',
             'German',
             'Greek',
             'Hungarian',
             'Italian',
             'Japanese',
             'Korean',
             'Norwegian',
             'Polish',
             'Portuguese',
             'Portuguese - Brazil',
             'Romanian',
             'Russian',
             'Spanish - Spain',
             'Spanish - Latin America',
             'Swedish',
             'Thai',
             'Turkish',
             'Ukrainian',
             'Vietnamese']

id =284080

header_column = ['id','name', 'age', 'release_date', 'developer', 'price', 'free to play'] + lang_list + [
    'num_lang'] + tags_list + ['num_tags']

def steam_info(id):
 spy_api = 'https://steamspy.com/api.php?request=appdetails&appid='+ str(id) +''
 steam_api = 'http://store.steampowered.com/api/appdetails?appids='+ str(id) +'&cc=us'

 if bool(requests.get(steam_api).json()[str(id)]['success']) == True:
     spy_api_page = requests.get(spy_api).json()
     steam_api_page = requests.get(steam_api).json()[str(id)]['data']

     # Dataframe
     if steam_api_page['type'] == 'game':


        d = pd.DataFrame(0, index=np.arange(len(header_column)), columns=header_column)

        # if steam_api_page['supported_languages'] is not None:
        try:
            for item in steam_api_page['supported_languages'].split(", "):
             if item in lang_list:
              d[item] = 1
        except Exception:
              pass
        # else:
        #     for item in steam_api_page['supported_languages']:
        #         if item in lang_list:
        #             d[item] = 1

        if isinstance(spy_api_page['tags'], dict) == True:
            for item in [*spy_api_page['tags'].keys()]:
             if item in tags_list:
              d[item] = 1

        d['id'] = id

        # if spy_api_page['name'] is not None:
        #     d['name'] = spy_api_page['name']
        # else:
        d['name'] = steam_api_page['name']

        d['age'] =  steam_api_page['required_age']

        if bool(steam_api_page['release_date']['date'] != 'Coming Soon') == True:
            if  len(str(steam_api_page['release_date']['date'])) == 12:
                d['release_date'] = datetime.strptime(steam_api_page['release_date']['date'], '%b %d, %Y')
            elif len(str(steam_api_page['release_date']['date'])) == 11:
                d['release_date'] = datetime.strptime(steam_api_page['release_date']['date'], '%b %d, %Y')
            elif len(str(steam_api_page['release_date']['date'])) == 8:
                d['release_date'] = datetime.strptime(steam_api_page['release_date']['date'], '%b %Y')
            else:
                d['release_date'] = 0
        else:
            d['release_date'] = 0
        # Api Price
        if steam_api_page['is_free'] == False:
            # if spy_api_page['price'] is not None and spy_api_page['price'] != '0' == True:
            #         d['price'] = int(spy_api_page['price']) / 100
            if bool('price_overview' in steam_api_page) == True:
                # if steam_api_page['price_overview']['initial'] is not None == True:
                    d['price'] = steam_api_page['price_overview']['initial'] / 100
            else:
                d['price'] = 0
        else:
            d['price']  = 0


        d['developer'] = spy_api_page['developer']


        try:
            d['num_lang'] = len(spy_api_page['languages'].split(", "))
        except Exception:
            pass

        if isinstance(spy_api_page['tags'], dict) == True:
            d['num_tags'] = len([*spy_api_page['tags'].keys()])

        d['free to play'] = steam_api_page['is_free']

        return d.iloc[0, :].to_dict()  # d.iloc[0, :].T.to_csv('steam_data_id_'+str(id)+'.csv')
     else:

      return pd.DataFrame(0, index=np.arange(len(header_column)), columns=header_column).iloc[0, :].to_dict()

 return pd.DataFrame(0, index=np.arange(len(header_column)), columns=header_column).iloc[0, :].to_dict()




