"""Mayavi/traits GUI visualization elements"""

# Authors: Christian Brodbeck <christianbrodbeck@nyu.edu>
#
# License: BSD (3-clause)

import os
import numpy as np

# allow import without traits
try:
    from mayavi.mlab import pipeline, text3d
    from mayavi.modules.glyph import Glyph
    from mayavi.modules.surface import Surface
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.tools.mlab_scene_model import MlabSceneModel
    from pyface.api import error
    from traits.api import (HasTraits, HasPrivateTraits, on_trait_change,
                            cached_property, Instance, Property, Array, Bool,
                            Button, Color, Enum, Float, Int, List, Range, Str)
    from traitsui.api import View, Item, Group, HGroup, VGrid, VGroup
except:
    from ..utils import trait_wraith
    HasTraits = HasPrivateTraits = object
    cached_property = on_trait_change = MlabSceneModel = Array = Bool = \
        Button = Color = Enum = Float = Instance = Int = List = Property = \
        Range = Str = View = Item = Group = HGroup = VGrid = VGroup = \
        Glyph = Surface = VTKDataSource = trait_wraith

from ..transforms import apply_trans


headview_item = Item('headview', style='custom', show_label=False)
headview_borders = VGroup(Item('headview', style='custom', show_label=False),
                          show_border=True, label='View')
defaults = {'mri_fid_scale': 1e-2, 'hsp_fid_scale': 3e-2,
            'hsp_fid_opacity': 0.3, 'hsp_points_scale': 4e-3,
            'mri_color': (252, 227, 191), 'hsp_point_color': (255, 255, 255),
            'lpa_color': (255, 0, 0), 'nasion_color': (0, 255, 0),
            'rpa_color': (0, 0, 255)}


def _testing_mode():
    """Helper to determine if we're running tests"""
    return (os.getenv('_MNE_GUI_TESTING_MODE', '') == 'true')


class HeadViewController(HasTraits):
    """
    Set head views for Anterior-Left-Superior coordinate system

    Parameters
    ----------
    system : 'RAS' | 'ALS' | 'ARI'
        Coordinate system described as initials for directions associated with
        the x, y, and z axes. Relevant terms are: Anterior, Right, Left,
        Superior, Inferior.
    """
    system = Enum("RAS", "ALS", "ARI", desc="Coordinate system: directions of "
                  "the x, y, and z axis.")

    right = Button()
    front = Button()
    left = Button()
    top = Button()

    scale = Float(0.16)

    scene = Instance(MlabSceneModel)

    view = View(VGrid('0', 'top', '0', Item('scale', label='Scale',
                                            show_label=True),
                      'right', 'front', 'left', show_labels=False, columns=4))

    @on_trait_change('scene.activated')
    def _init_view(self):
        self.scene.parallel_projection = True

        # apparently scene,activated happens several times
        if self.scene.renderer:
            self.sync_trait('scale', self.scene.camera, 'parallel_scale')
            # and apparently this does not happen by default:
            self.on_trait_change(self.scene.render, 'scale')

    @on_trait_change('top,left,right,front')
    def on_set_view(self, view, _):
        if self.scene is None:
            return

        system = self.system
        kwargs = None

        if system == 'ALS':
            if view == 'front':
                kwargs = dict(azimuth=0, elevation=90, roll=-90)
            elif view == 'left':
                kwargs = dict(azimuth=90, elevation=90, roll=180)
            elif view == 'right':
                kwargs = dict(azimuth=-90, elevation=90, roll=0)
            elif view == 'top':
                kwargs = dict(azimuth=0, elevation=0, roll=-90)
        elif system == 'RAS':
            if view == 'front':
                kwargs = dict(azimuth=90, elevation=90, roll=180)
            elif view == 'left':