#
#   Python GUI - Controls - PyObjC
#

from math import ceil
from Foundation import NSSize
import AppKit
import Components
import StdColors
from Colors import Color
from Fonts import Font
from GControls import Control as GControl

_ns_alignment_from_just = {
    'left':   AppKit.NSLeftTextAlignment,
    'center': AppKit.NSCenterTextAlignment,
    'centre': AppKit.NSCenterTextAlignment,
    'right':  AppKit.NSRightTextAlignment,
    'flush':  AppKit.NSJustifiedTextAlignment,
    '':       AppKit.NSNaturalTextAlignment,
}

_ns_alignment_to_just = {
    AppKit.NSLeftTextAlignment:      'left',
    AppKit.NSCenterTextAlignment:    'center',
    AppKit.NSRightTextAlignment:     'right',
    AppKit.NSJustifiedTextAlignment: 'flush',
    AppKit.NSNaturalTextAlignment:   '',
}

class Control(GControl):

    _vertical_padding = 5

    def get_title(self):
        return self._ns_cell().title()
    
    def set_title(self, v):
        self._ns_cell().setTitle_(v)
    
    def get_enabled(self):
        return self._ns_cell().enabled()
    
    def set_enabled(self, v):
        self._ns_cell().setEnabled_(v)
    
    def get_color(self):
        return StdColors.black
    
    def set_color(self, v):
        pass
            
    def get_font(self):
        return Font._from_ns_font(self._ns_cell().font())
    
    def set_font(self, f):
        self._ns_cell().setFont_(f._ns_font)
        
    def get_just(self):
        return _ns_alignment_to_just[self._ns_cell().alignment()]
    
    def set_just(self, v):
        self._ns_cell().setAlignment_(_ns_alignment_from_just[v])
    
    def _ns_cell(self):
        return self._ns_inner_view.cell()

#------------------------------------------------------------------------------

def ns_size_to_fit(ns_control, padding = (0, 0), height = None):
    # Set size of control to fit its contents, plus the given padding.
    # Height may be overridden, because some controls don't seem to
    # calculate it properly.
    # Auto sizing can result in fractional sizes, which seems to cause
    # problems when NS autoresizing occurs later. So we round the size up
    # to whole numbers of pixels.
    ns_control.sizeToFit()
    w, h = ns_control.frame().size
    pw, ph = padding
    ns_control.setFrameSize_((ceil(w + pw), ceil((height or h) + ph)))
