# -*- coding: utf-8 -*-

# Maya 2018 전용

import sys
import os
import logging
import maya.cmds as cmds
from PySide2 import QtGui
from PySide2 import QtWidgets
from PySide2 import QtCore
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
import maya.OpenMayaUI as omui
import xml.etree.ElementTree as xml
from cStringIO import StringIO

# wrapInstance
import pyside2uic as pysideuic
from shiboken2 import wrapInstance
logging.Logger.manager.loggerDict["pyside2uic.uiparser"].setLevel(logging.CRITICAL)
logging.Logger.manager.loggerDict["pyside2uic.properties"].setLevel(logging.CRITICAL)

def load_ui(ui_file):
    '''ui 파일 읽기'''
    parsed = xml.parse(ui_file)
    widget_class = parsed.find('widget').get('class') # QMainWindow
    form_class = parsed.find('class').text # Window

    with open(ui_file, 'r') as f:
        o = StringIO()
        frame = {}
        pysideuic.compileUi(f, o, indent=0)
        pyc = compile(o.getvalue(), '<string>', 'exec')
        exec pyc in frame
        form_class = frame['Ui_%s' % form_class]
        base_class = getattr(QtWidgets, widget_class)
    return form_class, base_class

def maya_main_window():
    '''마야 루트 윈도우 얻기'''
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)

class MyDockingWindow(MayaQWidgetDockableMixin, QtWidgets.QMainWindow):
    def __init__(self, parent=None):

        # 이전 창 삭제
        self.delete_instances()

        # 부모 클래스 초기화
        super(MyDockingWindow, self).__init__(parent)

        self.setWindowFlags(QtCore.Qt.Tool)

        # UI 파일 읽기
        form_class, base_class = load_ui('d:/lab/my.ui')
        self.ui = form_class()
        self.ui.setupUi(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

    def dockCloseEventTriggered(self):
        self.delete_instances()

    def delete_instances(self):
        '''창 삭제'''
        for obj in maya_main_window().children():
            if str(type(obj)) == "<class 'MyDockingWindow'>":
                if obj.__class__.__name__ == "MyDockingWindow":
                    obj.setParent(None)
                    obj.deleteLater()

    def deleteControl(self, control):
        if cmds.workspaceControl(control, q=True, exists=True):
            cmds.workspaceControl(control, e=True, close=True)
            cmds.deleteUI(control, control=True)

    def run(self):
        '''창 만들기'''
        self.setObjectName("MyMainDockingWindow")
        workspaceControlName = self.objectName() + 'WorkspaceControl'
        self.deleteControl(workspaceControlName)
        self.show(dockable=True, area='right', floating=False)
        cmds.workspaceControl(workspaceControlName, e=True, ttc=["AttributeEditor", -1], wp="preferred", mw=420)
        self.raise_()
        self.setDockableParameters(width=420)

# 시작점
w = MyDockingWindow(parent=maya_main_window())
w.run()