from src.app.database.utility.QueryExceptions import InvalidRequest
import src.app.domain.collections.portfolios.portfoliosQueries as portfolioQueries

from src.app.database.utility import SqlUtility


def parseTuplesAsPortfolioList(tuples):
    tupleList = []
    tupleCounter = 0

    for row in tuples:
        portfolio = parseTuplesAsPortfolioObject(row)
        tupleList += [portfolio]
        tupleCounter += 1

    return {'portfolios': tupleList, 'total': tupleCounter}


def parseTuplesAsPortfolioObject(queryTuple):
    if len(queryTuple) != 10:
        raise ValueError("Invalid amount of data in portfolio tuple")

    portfolioObject = {
        'id': queryTuple[0],
        'user_id': queryTuple[1],
        'name': queryTuple[2],
        'type': queryTuple[3],
        'currency': queryTuple[4],
        'market_value': float(queryTuple[5] or 0),
        'invested_amount': float(queryTuple[6] or 0),
        'cash_amount': float(queryTuple[7] or 0),
        'frozen_amount': float(queryTuple[8] or 0),
        'all_time_gains': float(queryTuple[9] or 0)
    }

    return portfolioObject


def validatePortfolioObject(portfolio):
    return None


def validateUserHasPortfolio(userId, portfolioId):
    request = portfolioQueries.getPortfolioByIdForUser(userId, portfolioId)
    queryResponse = SqlUtility.executeSelectRequest(request)

    if queryResponse == ():
        raise InvalidRequest('This user, if it exists, has no portfolio with this ID')

from src.app.database.utility.QueryExceptions import InvalidRequest
import src.app.domain.collections.portfolios.portfoliosQueries as portfolioQueries

from src.app.database.utility import SqlUtility


def parseTuplesAsPortfolioList(tuples):
    tupleList = []
    tupleCounter = 0

    for row in tuples:
        portfolio = parseTuplesAsPortfolioObject(row)
        tupleList += [portfolio]
        tupleCounter += 1

    return {'portfolios': tupleList, 'total': tupleCounter}


def parseTuplesAsPortfolioObject(queryTuple):
    if len(queryTuple) != 10:
        raise ValueError("Invalid amount of data in portfolio tuple")

    portfolioObject = {
        'id': queryTuple[0],
        'user_id': queryTuple[1],
        'name': queryTuple[2],
        'type': queryTuple[3],
        'currency': queryTuple[4],
        'market_value': float(queryTuple[5] or 0),
        'invested_amount': float(queryTuple[6] or 0),
        'cash_amount': float(queryTuple[7] or 0),
        'frozen_amount': float(queryTuple[8] or 0),
        'all_time_gains': float(queryTuple[9] or 0)
    }

    return portfolioObject


def validatePortfolioObject(portfolio):
    return None


def validateUserHasPortfolio(userId, portfolioId):
    request = portfolioQueries.getPortfolioByIdForUser(userId, portfolioId)
    queryResponse = SqlUtility.executeSelectRequest(request)

    if queryResponse == ():
        raise InvalidRequest('This user, if it exists, has no portfolio with this ID')
