'''
Author: Jason.Parks
Created: April 25, 2012
Module: core.moBuFile
Purpose: File convenience class
'''
from pyfbsdk import *
from common.core import globalVariables as gv
from common.diagnostic.pcsLogger import moBuLogger
from common.fileIO.parser_schema import ParseSchema
from common.fileIO.pcsPath import Path
from moBu.core.moBuCore import MoBuCore #@UnresolvedImport
#import P4
import getpass
import os
import re
import shutil

schemaObj = ParseSchema(mobu=1)

# eclipseSyntax
if False: from pyfbsdk_gen_doc import * #@UndefinedVariable @UnusedWildImport


class MoBuFile(MoBuCore):
	
	def __init__(self):
		""" MoBuFile.__init__():  set initial parameters """
		super(MoBuFile, self).__init__()
	
	def cleanDirs(self, folderPath='', dirExtension='.fbm'):
		''' Cleans viral .bck/.fbm folders from given folderPath
			Params:
				folderPath: director to clean
				dirExtension: extension to look for on end of dir
			Returns: True if cleaned any
			'''
		deleted = False
		if not folderPath:
			moBuLogger.error("No folderPath arg passed.")
			return False
		
		for root, dirs, unused in os.walk(folderPath):
			for _dir in dirs:
				dirPath = os.path.join(root, _dir)
				if Path(dirPath).isdir:
					if re.search(dirExtension, dirPath):
						try:
							shutil.rmtree(dirPath)
							deleted = True
						except WindowsError:
							moBuLogger.info("Failed to remove '%s'" % dirPath)
		return deleted
		
	def customFBFbxOptions(self, pLoad=False, saveAllTakes=True, allElements=True, selection=False, **kwargs):
		''' create save/load options
		Params:
			pLoad: True if loading, False if saving
			saveAllTakes: Set to False if save current take only
			allElements: Set to False and pass kwargs to save/load/merge specific elements
			selection: True to save selected only
		Returns: FBFbxOptions object
		'''
		if self.mobuVer == 2010:
			moBuLogger.warning("FBFbxOptions are not valid for 2010")
			return None
		
		elif self.mobuVer == 2012 or self.mobuVer == 2013 or self.mobuVer == 2014:
			# create object
			pFbxOptions = FBFbxOptions(pLoad)
			
			if not allElements:
				# set all ElementActions and Base properties to false
				pFbxOptions.SetAll(FBElementAction.kFBElementActionDiscard, False)
				baseProperties = ['BaseCameras',
								'CameraSwitcher', 'CameraSwitcherSettings',
								'CurrentCamera', 'CurrentCameraSettings',
								'GlobalLighting', 'GlobalLightingSettings',
								'Transport', 'TransportSettings',
								'EmbedMedia', 'SaveSelectedModelsOnly', ]
				for bProperty in baseProperties:
					exec('pFbxOptions.%s=False' % bProperty)	
	
				# process kwargs
				for key in kwargs:
					# check for non-strings passed in
					if not isinstance(kwargs[key], str):
						moBuLogger.error("A non-string type arg was passed in: '%s'" % kwargs[key])
					if 'kFBElementAction' in kwargs[key]:
						# FBPropertyElementAction
						exec('pFbxOptions.%s = FBElementAction.%s' % (key, kwargs[key]))
					else:
						# FBPropertyBase
						exec('pFbxOptions.%s=%s' % (key, kwargs[key]))	
	
			# save selected for saves
			if not pLoad and selection:
				pFbxOptions.SaveSelectedModelsOnly = True
			
			# skip takes
			if not saveAllTakes:
				currentTake = self.system.CurrentTake
				
				pTakeIndex = 0
				for take in self.scene.Takes:
					# save current take only
					if not pLoad:
						if not take.Name == currentTake.Name:
							pFbxOptions.SetTakeSelect(pTakeIndex, False)
					# merge no takes
					else:
						pFbxOptions.SetTakeSelect(pTakeIndex, False)
					pTakeIndex += 1
			
			# save ASCII
			pFbxOptions.UseASCIIFormat = True
		
			return pFbxOptions
		else:
			moBuLogger.error("Wrong version of MotionBuilder '%s'" % self.mobuVer)
	
	def fixThis(self, message=''):
		''' sends scene and email to T.A.
			Params:
				message: passed message for email
			Returns: True/False
		'''
		successes = 0
		
		#1. Note currentScene name for reload
		currentScene = self.sceneName
		
		#2. Enter notes
		if not message:
			result = FBMessageBoxGetUserValue("Send Message", "Can you tell me what you were doing?", "Nothing to say", FBPopupInputType.kFBPopupString, "Send scene", "Cancel")
			if result[0] == 1:
				message = result[1]
			elif result[0] == 2:
				moBuLogger.info("Cancelled mbCore.fixThis()")
				return False
		
		#3. Save to network location
		savePath = Path('%s/data/%s/fixThis' % (gv.schemaLocation, getpass.getuser()))
		saveFilePath = '%s/%s' % (savePath, Path(currentScene).basename())
		
		# make dir
		if not os.path.exists(savePath):
			os.makedirs(savePath)
			
		if self.savePCSoptions(pathFile=saveFilePath, quiet=True, pOptions=None, p4=False):
			moBuLogger.info("Saved scene to: '%s'" % saveFilePath)
			successes += 1
		else:
			moBuLogger.info("Failed to save scene to: '%s'" % saveFilePath)
			return False
			
		
		#4. Email TechArtist
		#TODO: email message
		_file = open(saveFilePath.replace('.fbx', '.txt'), "w")
		_file.write(message)
		_file.close()
		
		#5. Reload original scene
		if self.loadPCSoptions(pathFile=currentScene, quiet=False, pOptions=None):
			successes += 1
		else:
			moBuLogger.info("Failed to reload original scene: '%s'" % currentScene)
			
		if successes == 2:
			return True
		else:
			return False
	
	def loadPCSoptions(self, pathFile=None, quiet=False, pOptions=None):
		''' saves with customFBFbxOptions
		Params:
			pathFile: complete file path to save
			quiet: suppress messages
			pOptions: pre-made options
		Returns: True/False
		'''