# -*- coding: utf-8 -*-
import pymel.core as pm
import mtoa.utils as utils
import mtoa.ui.ae.utils as aeUtils
import maya.cmds as cmds
from mtoa.ui.ae.shaderTemplate import ShaderAETemplate
import maya.mel as mel

class AEaiImageTemplate(ShaderAETemplate):
    def filenameEdit(self, newFilename) :
        attr = self.nodeAttr('filename')
        cmds.setAttr(attr, newFilename, type="string")
        attr = self.nodeAttr('colorSpace')
        ignoreFileRules =  cmds.getAttr(self.nodeAttr('ignoreColorSpaceFileRules'))

        # if ignoreFileRules is enabled, we don't want to update the color space (#2843)
        if ignoreFileRules == 0:
            cmds.setAttr(attr, cmds.colorManagementFileRules(evaluate=newFilename), type="string")

    def LoadFilenameButtonPush(self, *args):
        basicFilter = 'All Files (*.*)'
        ret = cmds.fileDialog2(fileFilter=basicFilter, cap='Load Image File',okc='Load',fm=4)
        if ret is not None and len(ret):
            self.filenameEdit(ret[0])
            cmds.textFieldGrp("filenameImageGrp", edit=True, text=ret[0])

    def filenameNew(self, nodeName):
        #cmds.rowLayout(nc=3)
        cmds.rowLayout(nc=2, cw2=(360,30), cl2=('left', 'left'), adjustableColumn=1, columnAttach=[(1, 'left', -4), (2, 'left', 0)])
        path = cmds.textFieldGrp("filenameImageGrp", label="图像名称", changeCommand=self.filenameEdit)
        cmds.textFieldGrp(path, edit=True, text=cmds.getAttr(nodeName))
        cmds.symbolButton( image='navButtonBrowse.png', command=self.LoadFilenameButtonPush)

    def filenameReplace(self, nodeName):
        cmds.textFieldGrp( "filenameImageGrp", edit=True, text=cmds.getAttr(nodeName) )

    @staticmethod
    def editUVSet(newValue):
        try:
            if len(newValue) > 0:
                cmds.attrFieldGrp('aiImageUVCoords', edit=True, enable=False)
            else:
                cmds.attrFieldGrp('aiImageUVCoords', edit=True, enable=True)
            mel.eval('refreshAE')
        except:
            import traceback, sys
            traceback.print_exc(file=sys.__stderr__)

    def uvsetNew(self, attrName):
        cmds.setUITemplate('attributeEditorPresetsTemplate', pushTemplate=True)
        aeUtils.attrTextFieldGrp('aiImageUVSet', label='UV Set', attribute=attrName, changeCommand=AEaiImageTemplate.editUVSet)
        cmds.setUITemplate(popTemplate=True)

    def uvsetReplace(self, attrName):
        try:
            aeUtils.attrTextFieldGrp('aiImageUVSet', edit=True, attribute=attrName, changeCommand=AEaiImageTemplate.editUVSet)
        except:
            pass

    def uvcoordsNew(self, attrName):
        cmds.setUITemplate('attributeEditorPresetsTemplate', pushTemplate=True)
        enabled = True
        if len(cmds.getAttr('%s.uvset' % attrName.split('.')[0])) > 0:
            enabled = False
        cmds.attrFieldGrp('aiImageUVCoords', label='UV Coords', enable=enabled, attribute=attrName)
        cmds.setUITemplate(popTemplate=True)

    def uvcoordsReplace(self, attrName):
        try:
            enabled = True
            if len(cmds.getAttr('%s.uvset' % attrName.split('.')[0])) > 0:
                enabled = False
            cmds.attrFieldGrp('aiImageUVCoords', edit=True, enable=enabled, attribute=attrName)
        except:
            pass

##   In case we need an attribute "imageName" so that colorSpace is updated correctly
#    def imageNameConnect(self, attrName):
#        if not cmds.isConnected(self.nodeAttr('filename'), self.nodeAttr('imageName')):
#            cmds.connectAttr(self.nodeAttr('filename'), self.nodeAttr('imageName'))


    def setup(self):
        self.addSwatch()
        self.beginScrollLayout()
        
        self.beginLayout("图像属性", collapse=False)
        self.addCustom('filename', self.filenameNew, self.filenameReplace)
        self.addControl("filter", label="过滤器")
        
        self.addControl("mipmap_bias", label="纹理贴图偏差")
        self.addControl("multiply", label="相乘")
        self.addControl("offset", label="抵消")
        # self.addCustom('imageName', self.imageNameConnect, self.imageNameConnect)
    

        cmds.editorTemplate('AEcolorSpaceNew', 'AEcolorSpaceReplace', 'colorSpace', callCustom=True)
        self.addControl("ignoreColorSpaceFileRules", label="忽略色彩空间文件规则")
        self.addControl("autoTx", label="自动生成TX纹理")
        self.addSeparator()
        
        self.addControl("ignoreMissingTextures", label="忽略缺少纹理")
        self.addControl("missingTextureColor", label="缺少纹理颜色")
        self.endLayout()
        
        self.beginLayout("UV坐标", collapse=True)
        self.beginNoOptimize()
        self.addCustom('uvset', self.uvsetNew, self.uvsetReplace)
        self.addSeparator()
        self.addCustom('uvcoords', self.uvcoordsNew, self.uvcoordsReplace)
        
        self.addControl("soffset", label="抵消 U")
        self.addControl("toffset", label="抵消 V")
        
        self.addControl("swrap", label="包裹 U")
        self.addControl("twrap", label="包裹 V")
        
        self.addControl("sscale", label="比例 U")
        self.addControl("tscale", label="比例 V")
        
        self.addControl("sflip", label="反转 U")
        self.addControl("tflip", label="反转 V")
        
        self.addControl("swap_st", label="交换 UV")

        self.endNoOptimize()
        self.endLayout()
        
        pm.mel.AEdependNodeTemplate(self.nodeName)
        self.addExtraControls()
        self.endScrollLayout()

