import bpy
import datetime

from . properties import *
from . operators import *
from . sun_calc import Degrees, format_lat_long, degToRad, \
                       format_time, format_hms, Move_sun

#---------------------------------------------------------------------------
#
#   Draw the Sun Panel, sliders, et. al.
#
#---------------------------------------------------------------------------


class SunPos_Panel(bpy.types.Panel):

    bl_idname = "panel.SunPos_world"
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_context = "world"
    bl_label = "Sun Position and Power"
    bl_options = {'DEFAULT_CLOSED'}

    @classmethod
    def poll(cls, context):
        if context.area.type == 'PROPERTIES':
            return 1
        return 0

    def enable(self, layout):
        row = layout.row()
        split = row.split(percentage=.90)
        colL = split.column()
        colL.alignment = 'LEFT'
        colR = split.column()
        colR.alignment = 'RIGHT'
        colL.operator('world.sunpos_controller', 'Enable', icon='PLAY')
        colR.operator('world.sunpos_preferences', '', icon='PREFERENCES')
        Map.init_zoom_preference = True

    def disable(self, context, layout):
        p = context.scene.SunPos_pref_property
        if Map.init_zoom_preference:
            Map.zoom_preferences(bpy.context.user_preferences.inputs.invert_zoom_wheel,
                             bpy.context.user_preferences.inputs.invert_mouse_zoom)
            Hdr.zoom_preferences(bpy.context.user_preferences.inputs.invert_zoom_wheel,
                             bpy.context.user_preferences.inputs.invert_mouse_zoom)
        row = self.layout.row()
        if p.UseOneColumn:
            col1 = row.column()
            col2 = col1
        elif p.UseTimePlace:
            split = row.split(percentage=.3)
            col1 = split.column()
            col2 = split.column
()
        else:
            col1 = row.column()

        col1.operator('world.sunpos_controller', 'Disable', icon='X')
        if p.UseTimePlace:
            col2.operator_menu_enum('world.pdp_operator',
                'timePlacePresets', text=Sun.PlaceLabel)

    def show_preferences(self, context, layout):
        p = context.scene.SunPos_pref_property
        box = self.layout.box()
       
 row = box.row(align=True)
        row.alignment = 'CENTER'
        row.label(text="Preferences")
        col = box.column(align=True)
        col.label(text="Usage mode:")
        col.props_enum(p, "UsageMode")
        col.separator()

        if p.UsageMode == "NORMAL":
            cb = col.box()
            tr = cb.row()
            rr = tr.row(align=True)
            cs = rr.split()
            cl = cs.column()
            cr = cs.column()
                
            cl.label(text="World map options:")
            cl.operator_menu_enum('world.wmp_operator',
                          'mapPresets', text=Sun.MapName)
            cr.label(text="Display map in:")
            cr.props_enum(p, "MapLocation")
            col.separator()
            col.label(text="Show or use:")
            col.alignment = 'LEFT'
            col.prop(p, "UseOneColumn", text="Single column mode")
            col.prop(p, "UseTimePlace", text="Time/place presets")
            col.prop(p, "UseObjectGroup", text="Object group")
            col.prop(p, "ShowDMS", text="D\xb0 M' S\"")
            col.prop(p, "ShowNorth", text="North offset")
            col.prop(p, "ShowRefraction", text="Refraction")
            col.prop(p, "ShowAzEl", text="Azimuth, elevation")
            col.prop(p, "ShowDST", text="Daylight savings time")
            col.prop(p, "ShowRiseSet", text="Sunrise, sunset")
            col.separator()
        col.operator('world.sunpos_pref_done', 'Done', icon='QUIT')
        Sun.ShowRiseSet = p.ShowRiseSet

    def draw(self, context):
        sp = context.scene.SunPos_property
        p = context.scene.SunPos_pref_property
        layout = self.layout
        if Display.PREFERENCES:
            self.show_preferences(context, layout)
        elif Display.ENABLE:
            Sun.SP = sp
            Sun.PP = p
            self.enable(layout)
        else:
            Sun.SP = sp
            Sun.PP = p
            self.disable(context, layout)
        if Display.PANEL:
            if Sun.SP.IsActive:
                self.draw_panel(context, sp, p, layout)
            else:
                Display.setAction('ENABLE')

    def draw_panel(self, context, sp, p, layout):
        if p.UsageMode == "HDR":
            self.draw_environ_panel(context, sp, p, layout)
        elif p.UseOneColumn:
            self.draw_one_column(context, sp, p, layout)
        else:
            self.draw_two_columns(context, sp, p, layout)

    def draw_environ_panel(self, context, sp, p, layout):
        box = self.layout.box()
        toprow = box.row()
        row = toprow.row(align=False)
        row.alignment = 'CENTER'
        col = row.column(align=True)
        have_texture = False

        try:
            col.separator()
            col.label(text="Use environment texture:")
            col.prop_search(sp, "HDR_texture",
                context.scene.world.node_tree, "nodes", text="")
            col.separator()
            try:
                nt = bpy.context.scene.world.node_tree.nodes
                envTex = nt.get(sp.HDR_texture)
                if envTex:
                    if envTex.type == "TEX_ENVIRONMENT":
                        if envTex.image != None:
                            have_texture = True
                    if Sun.Bind.azDiff == 0:
                        if envTex.texture_mapping.rotation.z == 0.0:
                            Sun.Bind.azDiff = degToRad(90.0)
            except:
                pass
        except:
            pass
        try:
            col.label(text="Use sun object:")
            col.prop_search(sp, "SunObject",
                context.scene, "objects", text="")
            Sun.SunObject = sp.SunObject
        except:
            pass

        
        col.separator()
        col.prop(sp, "SunDistance")
        if not sp.BindToSun:
            col.prop(sp, "HDR_elevation")
        col.prop(sp, "HDR_azimuth")
        col.separator()
        toprow1 = box.row()
        row1 = toprow1.row(align=False)
        row1.alignment = 'CENTER'
        if not sp.BindToSun:
            row1.prop(sp, "BindToSun", toggle=True, icon="CONSTRAINT",
                text="Bind Texture to Sun ")
        else:
            row1.prop(sp, "BindToSun", toggle=True, icon="CONSTRAINT",
                text="Release binding")

        toprow2 = box.row()
        row2 = toprow2.row(align=False)
        row2.alignment = 'CENTER'
        row2.prop(sp, "ShowHdr", text="Sync Sun to Texture", toggle=True, icon='LAMP_SUN')
        if have_texture == False:
            row2.enabled = False
        elif sp.BindToSun:
            row2.enabled = False
        else:
            row2.enabled = True
        if have_texture == False:
            row1.enabled = False
        elif sp.ShowHdr:
            row1.enabled = False
        else:
            row1.enabled = True
        

    def draw_one_column(self, context, sp, p, layout):
        box = self.layout.box()
        toprow = box.row()
        row = toprow.row(align=False)
        row.alignment = 'CENTER'

        col = row.column(align=True)
        col.prop(sp, "UseSkyTexture", text="Cycles sky")
        if sp.UseSkyTexture:
            try:
                col.prop_search(sp, "SkyTexture",
                    context.scene.world.node_tree, "nodes", text="")
            except:
                pass
        col.prop(sp, "UseSunObject", text="Use object")
        if(sp.UseSunObject):
            try:
                col.prop_search(sp, "SunObject",
                    context.scene, "objects", text="")
            except:
                pass

        if p.UseObjectGroup:
            col.prop(sp, "UseObjectGroup", text="Object group")
            if sp.UseObjectGroup:
                Sun.verify_ObjectGroup()
                if len(Sun.Selected_objects) > 0:
                    col.operator('world.sunpos_clear_objects',
                       