#if 0 /*
# -----------------------------------------------------------------------
# copy_to_cd.py - Plugin for copying a movie to a cd
# -----------------------------------------------------------------------
# $Id: copy_to_cd.py,v 1.0 2004/01/20 05:44:05 phishman Exp $
#
# Notes: Copies the given file to a CD
#
# -----------------------------------------------------------------------
# $Log: copy_to_cd.py,v $
# Revision 1.0 2004/01/20 05:44:05 phishman
#
# -----------------------------------------------------------------------
# Freevo - A Home Theater PC framework
# Copyright (C) 2002 Krister Lagerstrom, et al. 
# Please see the file freevo/Docs/CREDITS for a complete list of authors.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MER-
# CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# ----------------------------------------------------------------------- */
#endif

import os
import time
import string
import sys
import threading
import re
import shutil

import config
import menu
import util
import plugin
import rc

import os

import string
import menu
import plugin
import time
import item
import re
import glob
import config

from gui.PopupBox import PopupBox
from gui.ConfirmBox import ConfirmBox
from gui.AlertBox import AlertBox
from gui.YesNoBox import YesNoBox

class BurnCDItem:
    def __init__(self,item,filename=None,plugin=None):
        self.item          = item
	self.menuw         = None
	self.plugin        = plugin 
	self.files         = []
	self.volume_name   = None
	self.burn_as_audio = 0

    def burn (self, arg=None, menuw=None):
	ConfirmBox(text=_('Start burning %s ?' % self.files),
                         handler=self.prepare_burning, default_choice=0).show()	

    def delete (self, arg=None, menuw=None):
	self.menuw = menuw
	ConfirmBox(text=_('Delete %s ?' % self.files),
                         handler=self.delete_now, default_choice=0).show()	

    def delete_now (self, arg=None, menuw=None):
	for a in self.files:
		os.unlink(a)
	self.menuw.back_one_menu(arg='reload')
	self.menuw.refresh
	

    def prepare_burning (self, arg=None, menuw=None):
	try:
	    for a in os.listdir("/tmp/burnlist"):
		os.unlink("/tmp/burnlist/" + a)
	except:
	    #AlertBox(text='"Aborted, could not empty /tmp/burnlist"')
	    #return
	    pass

	try:
	    if not os.stat("/tmp/burnlist"):
 	           os.makedirs("/tmp/burnlist", 0777)
	    else:
		   if os.listdir("/tmp/burnlist"):
			   AlertBox(text='Aborted, directory /tmp/burnlist not empty').show()
            		   return

        except:
	    AlertBox(text='Aborted, directory /tmp/burnlist already exists').show()
	    return
	    
     	for a in self.files:
	    path = re.split("\\/", a)
	    os.symlink(a, "/tmp/burnlist/" + path[-1])   

	self.start_burning(menuw=menuw)
	

    def start_burning (self, arg=None, menuw=None):
	self.menuw = menuw
	self.thread_burn = main_burn_thread(token=self)
        self.thread_burn.start()
	self.plugin.thread_burn = self.thread_burn
    

    def findFileFromItem (self) :
	if self.item.filename:
		self.volume_name = self.item.name
		self.files.append(self.item.filename)

    def findRelated (self,mode=0):
        self.files.append(self.item.filename)
	file = self.item.filename
	self.volume_name = self.item.name

        rexp = re.compile('(.*)/(.*)\.(.*)')
        result = rexp.search(file)
        name = result.group(2)
        dir = result.group(1)
        print 'File: ' + file
        print 'Name: ' + name
        print 'Dir: ' + dir;
        files = glob.glob( dir + '/' + name + '.*' )
        print 'Files '
        for k in files:
                if k == file:
                        continue
                result = rexp.search(k)
                ext = result.group(3)

                if mode==0 and (ext == 'fxd' or ext == 'jpg'):
                        continue

                print '  More file: ' + k
                print '     extension ' + ext
                self.files.append(k)

class main_burn_thread(threading.Thread):
    def __init__(self, token=None):
        threading.Thread.__init__(self)
	self.token = token
	self.running = 0
	self.status = ""


    def run(self, arg=None, menuw=None, token=None):
	self.running = 1
	self.status = "Creating disc image"
	print "start buring"

        """
        copy files onto a CD
	"""
	if not self.token.volume_name:
		self.token.volume_name = self.item.type

        ###CHANGE###
        #Temp file that cdrecord will use when making the cd-image (needs atleast 650mb's free)
        temp_file = '/tmp/image.img'

        ###CHANGE###
        #The speed at which you would like to record
        record_speed = '8'

        ###CHANGE###
        #The device used on the SCSI-BUS (cdrecord -scanbus should show you)
        block_dev = 'ATAPI:0,0,0'

        os.system('mkisofs -f -U -V "%s" -o %s %s' % (self.token.volume_name,temp_file,"/tmp/burnlist/"))
	self.status = "Burning image to CD"
        os.system('cdrecord -eject -v speed=%s dev=%s %s' % (record_speed,block_dev,temp_file))
	os.unlink(temp_file)
	self.running = 0 
        return

class PluginInterface(plugin.ItemPlugin):        
	
    def __init__(self):
        plugin.ItemPlugin.__init__(self)
        self.device = ''
	self.item   = None
        self.thread_burn = None 

    def show_t_status (self, arg=None, menuw=None):
        AlertBox(text=_('Burning status: %s' % self.thread_burn.status )).show()


    def actions(self, item):
        self.item = item
	to_return = [ ]
	print self.thread_burn
	
	if self.thread_burn and self.thread_burn.running == 1:
	   to_return.append( (self.show_t_status, 'Show burning status' ));
	   return to_return 

	if not ( item.type == 'audio' or item.type == 'image' or item.type == 'video' or item.type == 'dir' ):
	   return to_return

	#Any item that is just one file
	try:
	    cur = BurnCDItem(item=item, plugin=self)
	    cur.findFileFromItem()
	    #cur.addFilesFromItem()
	    if cur.files:
              to_return.append( ( cur.burn, _('Copy this file to CD')) ) 
	except:
	    print "Not possible to cur.findFileFromItem"
	    pass

	#single video file
	try:
	 if item.filename and item.type == 'video':
           cur = BurnCDItem(item=item, plugin=self)
	   cur.findRelated()
	   cur2 = BurnCDItem(item=item, plugin=self)
	   cur2.findRelated(mode=1)

	   if cur.files:
             to_return.append(( cur.burn, _('Copy %s, and related, to CD' % item.name)) )
             to_return.append(( cur2.delete, _('Delete %s, and related' % item.name)) )
	except:
	 pass

	#joined video files
	try:
 	 if not item.filename:
            if item.type == 'video':
               for a in item.subitems:
                   if a.filename:
                       cur = BurnCDItem(item=a, plugin=self)
		       cur.findRelated()

		       cur2 = BurnCDItem(item=a, plugin=self)
		       cur2.findRelated(mode=1)

		       if cur.files:
                          to_return.append(( cur.burn,    _('Copy %s, and related, file to CD' % a.name)) )
                          to_return.append(( cur2.delete, _('Delete %s, and related' % a.name)) )
	except:
	 pass

	#dirs

        return to_return 
