# -*- coding: utf-8 -*-

"""
Convert between objects and flypy representations.
"""

from __future__ import print_function, division, absolute_import
import ctypes

import flypy as nb
from flypy import typing
from .representation import stack_allocate, byref, c_primitive

#===------------------------------------------------------------------===
# Object Conversion
#===------------------------------------------------------------------===

ctypes_type_memo = {}

def fromobject(value, type):
    """
    Convert a Python value to a flypy representation according to `type`
    (e.g. list -> List)
    """
    cls = type.impl
    if hasattr(cls, 'fromobject') and not isinstance(value, cls):
        return cls.fromobject(value, type)
    return value


def toobject(value, type):
    """
    Convert a flypy value to a Python representation (e.g. List -> list)
    """
    cls = type.impl
    if hasattr(cls, 'toobject'):
        return cls.toobject(value, type)
    return value


def toctypes(value, type, keepalive, valmemo=None, typememo=None):
    """
    Convert a flypy object given as a Python value to a low-level ctypes
    representation.

    Returns (ctypes_value, keep_alive)
    """
    from flypy.types import int8