# Import the Flask Framework
from flask import Flask
from flask import render_template
from flask import url_for
from flask import request
from flask import Flask, session, redirect, escape
import json

#import ndb database
from google.appengine.ext import ndb

app = Flask(__name__)
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.

#group types---------------------------------------------------//
PLAYER_KEY = "PLAYER"
GAME_KEY = "GAME"

current_GuestBook = ""

"""**********************************************************************************************************
Player class
**********************************************************************************************************"""
class Player(ndb.Model):

    #Identity--------------------------------------------------------//
    username = ndb.StringProperty()
    password = ndb.StringProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)

    #gameplay---------------------------------------//
    word = ndb.StringProperty()
    game_state = ndb.StringProperty()
    bad_guesses = ndb.IntegerProperty()
    games_won = ndb.IntegerProperty()
    games_lost = ndb.IntegerProperty()

    #contribution--------------------------------------//
    games_created = ndb.IntegerProperty()
    games_played = ndb.IntegerProperty()

    @classmethod
    #static class that sorts the player
    def query_entity(cls, ancestor_key):
        return cls.query(ancestor=ancestor_key).order(-cls.date)

    #Reset my own ass
    def ResetPlayerStatus(self, wordLength):

        self.word = ""
        for num in range(0,wordLength):
            self.word += "_"

        self.games_played += 1
        self.game_state = "ONGOING"
        self.bad_guesses = 0

        #Must store it back in!!!
        self.put()

"""**********************************************************************************************************
Game class
**********************************************************************************************************"""
class Game(ndb.Model):

    #Properties--------------------------------------------------------//
    game_id = ndb.StringProperty()
    hint = ndb.StringProperty()
    word_length = ndb.IntegerProperty()

    #game properties-------------------------------------------------//
    wins = ndb.IntegerProperty()
    losses = ndb.IntegerProperty()

    @classmethod
    #static class that sorts the player
    def query_entity(cls, ancestor_key):
        return cls.query(ancestor=ancestor_key).order(-cls.word_length)


"""**********************************************************************************************************
Get list of entity
**********************************************************************************************************"""
def Get_ListOfEntity(key):

    #Gey player base entity-----------------------------------------------//
    ancestor_key = ndb.Key("base", key)
    lsitOfEntity = []

    if(key == PLAYER_KEY):
        lsitOfEntity = Player.query_entity(ancestor_key).fetch(20)
    elif(key == GAME_KEY):
        lsitOfEntity = Game.query_entity(ancestor_key).fetch(20)

    return lsitOfEntity

"""**********************************************************************************************************
Add player
**********************************************************************************************************"""
def AddPlayer(username, password):

    print("Adding player: " + username + "  pw: " + password + ".............")

    #check if existing------------------------------------------------//
    notExisting = True
    playerList = Get_ListOfEntity(PLAYER_KEY)
    for i in playerList:
        if username == i.username:
            notExisting = False
            print("Sorry, not adding player, existing username :(")
            break

    if notExisting == True:
        player = Player(parent=ndb.Key("base", PLAYER_KEY), username = username, password = password,
                        word = "ASS", game_state = "ONGOING", bad_guesses = 0, games_won = 0, games_lost = 0, games_created = 0,
                        games_played = 0)
        player.put()

    return notExisting

"""**********************************************************************************************************
Get player as a json
**********************************************************************************************************"""
def GetPlayer(username):

    lsitOfEntity = Get_ListOfEntity(PLAYER_KEY)

    for i in lsitOfEntity:
        if i.username == username:
            return i

    return None

"""**********************************************************************************************************
save player
**********************************************************************************************************"""
def SavePlayer(username):

    player = GetPlayer(username)
    player.put()

"""**********************************************************************************************************
save game
**********************************************************************************************************"""
def SaveGame(game_id):

    game = GetGame(game_id)
    game.put()

"""**********************************************************************************************************
Add game
**********************************************************************************************************"""
def AddGame(game_id, hint, word_length):

    game = Game(parent=ndb.Key("base", GAME_KEY), game_id = game_id, hint = hint, word_length = word_length, wins = 0, losses = 0)
    game.put()

"""**********************************************************************************************************
Get game
**********************************************************************************************************"""
def GetGame(game_id):

    lsitOfEntity = Get_ListOfEntity(GAME_KEY)

    for i in lsitOfEntity:
        if i.game_id == game_id:
            return i

    return {}


"""**********************************************************************************************************
Delete game
**********************************************************************************************************"""
def DeleteGame(game_id):
    GetGame(game_id).key.delete()

"""**********************************************************************************************************
Get list of dict of games from db
**********************************************************************************************************"""
def ListOfDicts_Game():

    gameList = Get_ListOfEntity(GAME_KEY)
    finalList = []

    for i in gameList:

        gameDict = {}   #dict
        gameDict['hint'] = i.hint
        gameDict['word_length'] = i.word_length
        gameDict['game_id'] = i.game_id
        finalList.append(gameDict)

    return finalList

"""**********************************************************************************************************
Temporary: add list of games to the db
**********************************************************************************************************"""
def AddSomeGamesToDB():

    AddGame("fuck", "dick", 22)

"""**********************************************************************************************************
Check if user name and pw in database
**********************************************************************************************************"""
def CheckPlayerInDB(username, password):

    #get list of players-----------------------------------------------------------//
    playerList = Get_ListOfEntity(PLAYER_KEY)

    for i in playerList:
        if i.username == username and i.password == password:
            return True

    return False

"""**********************************************************************************************************
clear database:
**********************************************************************************************************"""
def ClearDatabase(key):

    lsitOfEntity = Get_ListOfEntity(key)

    for i in lsitOfEntity:
        i.key.delete()
