//by @xeviff 
/* HARDCODED */
def skipAudioCheck = true
def show_error_line=true
def ubuntu_desktop=true


/** RUTAS **/ 
def root = '/pelis/'
def rutaOK = root+"Pelis/plain/"
def ruta = rutaOK
def ruta_docu = root+"Documentales/plain/"
def ruta_anime = root+"Pelis_anime/"
def ruta_animacion = root+"Pelis_animacion/"
def ruta_infantil = root+"Pelis_infantiles/"
def ruta_familiar = root+"Pelis_familiar/"
def ruta_esp = root+"Pelis_esp/plain/"
def ruta_latina = root+"Pelis_lat/"
def ruta_cat = root+"Pelis_cat/"
def ruta_retro = root+"Pelis_retro/plain/"
def ruta_estrenos = root+"Pelis_estrenos/plain/"
def ruta_classic = root+"Pelis_classic/"
def ruta_asiaticas = root+"Pelis_asiaticas/"

def rutaKO = root+"error/"
/**********/


//*****************************************************************************************/
//*****************************************************************************************/
//*****************************************************************************************/
try { //empieza el script

	//sanity check
  	if (!sanityCheck(tmdbid)) return '@@@@@@ Names Sanity Check KO @@@@@@@ --> New name: '+localize.Spanish.n+' with tmdb='+tmdbid

	if (ext==~/jpg|nfo|png|url/) {
		return fn
	}
	else if (ext!="mkv" && ext!="avi" && ext!="mp4") {
		throw new Exception("[formato_fichero_noestarndar]")
	}
	/********************************/


	/*************************************************************************************************************/
	/****  Carpeta / tipo contenido ******************************************************************************/
	/*************************************************************************************************************/

	//inits
	def tipoYaSeteado=false
	def prodCountries=info.ProductionCountries
	def certifications=info.Certifications
	def numPaises = info.ProductionCountries.size()
	def llengu = {try {def langs=[]; for (lan in languages) langs.add(lan.toString()); return langs } catch(err) {[]}}()
	def audioLlengu = {try {def langs=[]; for (lan in audioLanguages) langs.add(lan.toString()); return langs } catch(err) {[]}}()

	//animacion (no concluyente)
	def tieneAnimacion = genres.any{ it =~ /Anima.i.n/}
	//familiar (no conclud)
	def tieneFamiliar = genres.any{ it =~ /Familia|Family/}
	//docu
	def esDocu = genres.any{ it =~ /Documental|Documentary|Reality/} && !(localize.English.n =~ /Jackass/)
	//Anime ---------- (Animacion encara no es pot perquè depen del infantil)
	def esAnime = false
	if (tieneAnimacion && info.ProductionCountries.contains("JP") && (!llengu.isEmpty() ? llengu.contains('jpn') : true)) {
		esAnime = (numPaises==1 || anime || country=="JP") 
		&& ["nemo"].any{!localize.English.n.toLowerCase().contains(it)}
	}
	tipoYaSeteado = esDocu || esAnime

	//***** familiar vs infantil ****
	def esFamiliar = tieneFamiliar
	def	infantil = false

	if (!tipoYaSeteado) {
		def tieneCertificacion = info.Certifications!=null && info.Certifications.size()!=0

		if (tieneFamiliar && tieneAnimacion) {
			def noTanInfantil = info.Certifications.US ==~/PG-13/ && info.Certifications.ES!="7"
			if (!noTanInfantil) infantil = true
		}
		else if (tieneAnimacion) {
			if (tieneCertificacion) {
					infantil = info.Certifications.US=="G"
						|| info.Certifications.ES==~/Ai|APTA/
						|| info.Certifications.DE==~/0/
						|| info.Certifications.IT=="T" 
						|| info.Certifications.IE=="G" 
						|| info.Certifications.LT=="V" || info.Certifications.RU ==~ /6.+/
						|| info.Certifications.BR=="L"
						|| info.Certifications.NO=="A"
						|| info.Certifications.FR=="U"
			} else {
				def titulosInfantiles = ['boonie bears', 'the jungle bunch']
				if (titulosInfantiles.any { localize.English.n.toLowerCase().contains(it) })
					infantil = true
			}
		} else if (!esFamiliar) {
			if (tieneCertificacion && (
				 info.Certifications.US=="G"
				)) {
				esFamiliar = true //posem a familiar pelis de nens que no son animacio
			}
		}
		tipoYaSeteado = tipoYaSeteado || infantil
	}

	//animacion
	def esAnimacion = tieneAnimacion && !infantil
	tipoYaSeteado = tipoYaSeteado || esAnimacion

	//***  española ***
	def espanyola = false
	def catalana = false
	if (!tipoYaSeteado && info.ProductionCountries.contains("ES")) {
		espanyola=
				(numPaises==1 || (numPaises==2 && prodCountries.any{ it=~/AR|PT/ }))
			||	{ try { info.Network =~ /(?i)\bFLIXOL.\b|\b.?TVE\b/ } catch (e) { false } }()
			||	({ try { info.ProductionCompanies.any{it =~ /.?TVE|ESDIP|Canal Sur|Canal\+|Telecinco/}}catch(e){false}}() && llengu.size()==1?llengu[0]=="spa":false)
			||	(info.Certifications.size()==1 && info.Certifications.ES!=null) 
			||	llengu.size()==1 && llengu[0]=="spa"
			||	(movie.alternativeTitles.size()==1 && movie.alternativeTitles.ES!=null)
			||	(country=="ES" && (!llengu.isEmpty() ? llengu.size()==1 && llengu[0]!="eng" : true))
		if (espanyola) catalana = llengu.contains('cat')
		tipoYaSeteado = tipoYaSeteado || espanyola
	}

	//asiaticas
	def asiatica = false
	if (!tipoYaSeteado) {
		def paisesAsiaticos = ["CN", "HK", "JP", "KP", "KR", "TH", "NP", "TW", "PH", "MO", "IN", "AE", "VN"]
		def paisesIntersec=0
		def languajAsia = ["zho", "kor", "tha", "vie", "jpn", "ind", "vie"]
		def machingLanguages = languajAsia.intersect(llengu).size()
		asiatica = machingLanguages == languajAsia.size()
				|| paisesAsiaticos.any{ country==it }
				|| (numPaises != 0 && {((paisesIntersec=paisesAsiaticos.intersect(prodCountries).size()) == numPaises || (/*en observacion*/paisesIntersec!=0 && !llengu.contains('eng')) ) }())
				|| (languajAsia.any{audioLlengu.contains(it)} && prodCountries.any{paisesAsiaticos.contains(it)} && llengu.any{languajAsia.contains(it)} )
				|| {try {director.contains("Takeshi Kitano")} catch (e) {false}}()
				|| (machingLanguages > 0 && primaryTitle!=null && localize.English.n!=primaryTitle)
			
		tipoYaSeteado = tipoYaSeteado || asiatica
	}

	//***  latina ***
	def latina = false
	if (!tipoYaSeteado) {
		def paisesLatinos = ["MX", "AR"]
		latina = {try {paisesLatinos.contains(country)} catch (e) {false}}()
			    || (numPaises != 0 && paisesLatinos.intersect(info.ProductionCountries).size() == numPaises)
                || info.productionCompanies.any{it=~/Corazón Films/}
	}

	//////////////////////////////////////////////
		//tria
	if (esDocu) ruta = ruta_docu
	else if (esAnime) ruta = ruta_anime
	else if (infantil) ruta = ruta_infantil
	else if (esAnimacion) ruta = ruta_animacion
	else if (catalana) ruta = ruta_cat
	else if (espanyola) ruta = ruta_esp
	else if (latina) ruta = ruta_latina
	else if (asiatica) ruta = ruta_asiaticas
	else if (esFamiliar) ruta = ruta_familiar
	else if (y<1980) ruta = ruta_classic
	else if (y<2000) ruta = ruta_retro
	if (ruta==rutaOK && y>=2021) ruta = ruta_estrenos
	/********************************************/
	/**************************************/
	
	/*** RESULTADO FINAL ***/
	def inicial = (ruta==rutaOK || ruta==ruta_retro) ? getInicial() : ''
	def tmdb = " {tmdb-"+tmdbid+"}"
	def carpetaPeli = localize.Spanish.plex.name + tmdb + '/'

	return ruta + inicial + carpetaPeli + fn

} catch (err) {	

	if (show_error_line) {
		String str= err.getStackTrace().toString()
		def pattern = ( str =~ /groovy.(\d+)./   )
		return " Error at line number = " + pattern[0][1] + ". more: "+str
	}

	def rutaMotivoErr
	def msgErr = err.getMessage()
	if (msgErr=="[formato_fichero_noestarndar]" || msgErr=="[video_roto]")
		rutaMotivoErr="/fichero/"
	else if (msgErr=="[genero_no_especificado]" || msgErr=="[certificado_edad_no_especificado]") {
		rutaMotivoErr="/themoviedb/"
	} else if (msgErr.startsWith("[idioma_audio")) {
		rutaMotivoErr="/audio/"
	} else {
		def errSplitted = msgErr.split("\\-")
		return msgErr
		if (errSplitted==null) {
			rutaMotivoErr="/error_desconocido/"
		} else  {
			def errType = errSplitted[0]
			if (errType=="[formato_audio_no_encontrado")
				rutaMotivoErr="/audio/"
			else if (errType.startsWith("[idioma_audio"))
				rutaMotivoErr="/idioma/"
			else {
				String str2= err.getStackTrace().toString()
				def pattern2 = ( str2 =~ /groovy.(\d+)./   )
				return " Error at line number = " + pattern2[0][1]
			}
		}
	}
	
	def resultado = rutaKO + rutaMotivoErr + msgErr + '/' + fn
	
	return resultado
}



/********************************************************/
/********************************************************/
/************** FUNCIONES *******************************/
/********************************************************/
/********************************************************/
def getInicial () {
	def nomIngles = localize.English.n
	if (nomIngles.startsWith("The ") || nomIngles.startsWith("A "))
		nomIngles = nomIngles.replaceFirst("The ",'').replaceFirst("A ",'')
	def ini0 = nomIngles[0].toUpperCase()
	def iniClear = nomIngles.size()>1 ? ini0.replaceAll(/[¡¿'#*\(]/,nomIngles[1].toUpperCase()) : ini0
	def inicial = iniClear.replaceAll(/[0-9]/,'#')+'/'
	return inicial
}
def sanityCheck(newId) {
	def oldId = fn.find(/\{tmdb-\d+\}/)?.find(/\d+/)
	return oldId!=null ? oldId  == newId.toString() : true
}
/***********/