"""
.. code-block:: javascript

    import { Image } from 'react-native'

A Layer Group with Bitmap as child or a Shape Layer with an Image as a fill
can be tagged as **Image**. The name of the layer will be the name of the
image source generated.

"""
from sketch_components.utils import combine_styles, small_camel_case
from .commons import StyleSheet
from .component import Component
from ..props import Prop, Props, PropTypes, EdgeInsetsPropType, \
    StyleSheetPropType, ImageSourcePropType, \
    ImageStylePropTypes


class Image(Component):
    def __init__(self, source_name=None, source_path=None, props=None,
                 parent=None, layer=None):
        super(self.__class__, self).__init__(parent=parent, layer=layer)
        self.name = 'Image'
        self.path = 'react-native'
        self.is_default = False
        self.props = Props({
            'style': StyleSheetPropType(ImageStylePropTypes),
            'source': ImageSourcePropType,
            'defaultSource': PropTypes.oneOfType([PropTypes.shape({
                'uri': PropTypes.string, 'width': PropTypes.number,
                'height': PropTypes.number,
                'scale': PropTypes.number}), PropTypes.number]),
            'accessible': PropTypes.bool,
            'accessibilityLabel': PropTypes.node,
            'blurRadius': PropTypes.number,
            'capInsets': EdgeInsetsPropType,
            'resizeMethod': PropTypes.oneOf(['auto', 'resize', 'scale']),
            'resizeMode': PropTypes.oneOf(
                ['cover', 'contain', 'stretch', 'repeat', 'center']),
            'testID': PropTypes.string,
            'onLayout': PropTypes.func,
            'onLoadStart': PropTypes.func,
            'onProgress': PropTypes.func,
            'onError': PropTypes.func,
            'onPartialLoad': PropTypes.func,
            'onLoad': PropTypes.func,
            'onLoadEnd': PropTypes.func
        })
        self.update_props(props)
        self.is_self_closing = True
        self.source_name = source_name
        self.source_path = source_path

    def update_dependencies(self):
        for child in self.children:
            self.dependencies.add(child.import_statement())
            if not child.is_exportable_component():
                child.update_dependencies()
                self.dependencies.update(child.dependencies)
        from mako.template import Template
        if self.source_name and self.source_path:
            image_source_dependency = Template(
                """import ${name} from '${path}'""").render(
                name=self.source_name,
                path=self.source_path)
            self.dependencies.add(image_source_dependency)

    @classmethod
    def create_component(cls, sketch_layer, parent=None):
        if sketch_layer.component:
            props = sketch_layer.component.get_react_native_props()
        else:
            props = dict()
        style = props.get('style', Prop(dict())).value

        source_path = ''
        source_name = ''

        if sketch_layer.name is not None and sketch_layer.image is not None:
            source_name = small_camel_case(sketch_layer.name)
            sketch_layer.image.set_image_source(source_name)
            source_path = sketch_layer.image.get_image_source()
        elif sketch_layer.is_layer_group():
            image_layer = None
            for layer in sketch_layer.layers:
                if layer.is_image_layer():
                    image_layer = layer
            if (image_layer is not None and
                    image_layer.name is not None and
                    image_layer.image is not None):
                source_name = small_camel_case(image_layer.name)
                image_layer.image.set_image_source(source_name)
                source_path = image_layer.image.get_image_source()
        elif sketch_layer.is_shape_group():
            if (sketch_layer.style and sketch_layer.style.fills and
                    sketch_layer.style.fills[0].image):
                source_name = small_camel_case(sketch_layer.name)
                sketch_layer.style.fills[0].image.set_image_source(source_name)
                source_path = sketch_layer.style.fills[
                    0].image.get_image_source()

        if props.get('source', None) is None and source_name != '':
            props['source'] = Prop(source_name, is_literal=True)
        elif props.get('source') is not None:
            source_path = ''
            source_name = ''

        props.update(
            {'style': StyleSheet(
                combine_styles(sketch_layer.get_css_view_styles(), style),
                name=sketch_layer.name)})
        component = Image(source_name=source_name, source_path=source_path,
                          props=props, parent=parent,
                          layer=sketch_layer)
        for layer in sketch_layer.layers:
            if (layer.is_shape_group() and
                    layer.hasClippingMask or
                    layer.is_rectangle_shape() or
                    layer.is_oval_shape()):
                child = layer.get_react_component(pass_styles=True,
                                                  parent=component)
                if child:
                    component.add_child(child)
        # TODO: Remove after bug in react native is fixed
        if (component.props['style'].styles['borderRadius']) is not None and (
                component.props['style'].styles['borderRadius'] > 0):
            component.props['style'].styles['backgroundColor'] = None
        return component
