#
# $Id: alcspecialobjs.py 584 2006-08-11 12:48:53Z Robert The Rebuilder $
#
#    Copyright (C) 2005-2006  Alcugs pyprp Project Team
#    See the file AUTHORS for more info about the team
#
#    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
#    MERCHANTABILITY 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
#
#    Please see the file COPYING for the full license.
#    Please see the file DISCLAIMER for more details, before doing nothing.
#

# Help library

try:
    import Blender
    try:
        from Blender import NMesh
    except Exception, detail:
        print detail
except ImportError:
    pass

import dircache, os, StringIO
from os.path import *
from binascii import *
import alcconfig
from alcGObjects import *
from alcurutypes import *
from alc_Classes import *
from alc_AbsClasses import *
from alcprpfile import *
from alcxmlparser2 import *

#layers
splayer=[3]

class alcBook:
    def __init__(self,parent):
        self.book=None
        self.age=parent
        self.pages=[]
        self.resmanager=parent.resmanager
    
    
    def find(self,selection=0,create=1):
        if selection:
            l = Blender.Object.GetSelected()
        else:
            l = Blender.Object.Get()
        for obj in l:
            if obj.getType()=="Mesh":
                try:
                    p=obj.getProperty("book")
                    if p.getData()==1:
                        self.book=obj
                        self.findAllPages(selection)
                        return
                except AttributeError:
                    pass
        #Not Found
        if create:
            #obj = Blender.Object.New("Mesh","xBook")
            obj = alcCreateBox("xBook",10)
            global splayer
            obj.layers = splayer
            obj.drawType = 2
            obj.addProperty("book",1)
            obj.addProperty("AgeSDLHook",False,'BOOL')
            self.book=obj
            self.findAllPages(selection)
        else:
            self.book=None

    
    def addProp(self,name,val):
        if self.book==None:
            self.find()
        if name=="SequencePrefix":
            self.age.setSeq(int(val))
        addProp(self.book,name,val)

    
    def setAge(self,builtin=1):
        if self.book==None:
            self.find()
        for opt in self.age.options:
            self.addProp(opt[0],opt[1])
            #print "adding opt",
            #print opt
        try:
            #print "prop list"
            #print self.book.getAllProperties()
            seq=self.book.getProperty("SequencePrefix")
            seq=int(seq.getData())
        except AttributeError:
            raise RuntimeError, "An age must have a valid sequence prefix"
        print self.age.pages
        for page in self.age.pages:
            self.addPage(page.name,page.num,page.hide,page.type)

    def getAge(self,selection=0):
        #self.age=age
        #self.resmanager.base=self.age.base
        for opt in self.book.getAllProperties():
            if opt.getName()!="book":
                self.age.addOpt(opt.getName(),opt.getData())
        self.findAllPages(selection)
        for page in self.pages:
            #if page.type in (0x04,0x00):
            self.age.addPage(page.name,page.num,page.hide,page.type)

    
    def addPage(self,name,num=0,hide=0,type=0):
        p=self.findPage(num)
        #print num,p.num
        assert(num==p.num)
        p.setName(name)
        p.setHide(hide)
        p.setType(type)


    def findPage(self,num,selection=0):
        for page in self.pages:
            #print "check %i,%i" %(page.num,num)
            if page.num==num:
                return page
        page=alcPage(self)
        page.find(num,selection)
        assert(page.num,num)
        self.pages.append(page)
        return page

    
    def findAllPages(self,selection=0):
        if selection:
            l = Blender.Object.GetSelected()
        else:
            l = Blender.Object.Get()
        for obj in l:
            if obj.getType()=="Mesh":
                try:
                    p=obj.getProperty("page")
                    num=p.getData()
                    namecheck=getProp(obj,"name")
                    if num==-1 and namecheck=="BuiltIn":
                        for bugcheck in l:
                            if bugcheck.getType()=="Mesh":
                                bugnum=getProp(bugcheck,"page")
                                if bugnum==-2:
                                    addProp(bugcheck,"page",-1)
                        addProp(obj,"page",-2)
                        num=-2
                    elif num==-2 and namecheck=="Textures":
                        for bugcheck in l:
                            if bugcheck.getType()=="Mesh":
                                bugnum=getProp(bugcheck,"page")
                                if bugnum==-1:
                                    addProp(bugcheck,"page",-2)
                        addProp(obj,"page",-1)
                        num=-1
                    self.findPage(num,selection)
                except AttributeError:
                    pass
        #Not Found
    
    
    def save2xml(self):
        path = self.age.base + "/" + self.age.name
        f=file(path + "/xbook.xml","w")
        f.write("<?xml version=\"1.0\"?>\n<book version=\"1\">\n")
        f.write("  <sequenceprefix>%i</sequenceprefix>\n" %self.age.getSeq())
        for page in self.age.pages:
            f.write("  <page>\n")
            f.write("    <name>%s</name>\n" % page.name)
            f.write("    <num>%i</num>\n" % page.num)
            f.write("    <hide>%i</hide>\n" % page.hide)
            f.write("    <type>%i</type>\n" % page.type)
            f.write("  </page>\n")
        f.write("""</book>""")


class alcPage:
    def __init__(self,parent):
        self.book=parent
        self.resmanager=parent.resmanager
        #
        self.num=0
        self.name="unnamed"
        self.type=0
        self.hide=0
        self.page=None #BlenderObject
    
    
    def find(self,num=0,selection=0,create=1):
        self.num=num
        if selection:
            l = Blender.Object.GetSelected()
        else:
            l = Blender.Object.Get()
        for obj in l:
            if obj.getType()=="Mesh":
                try:
                    p=obj.getProperty("page")
                    if p.getData()==num:
                        self.page=obj
                        try:
                            self.type=obj.getProperty("type").getData()
                        except AttributeError:
                            pass
                        try:
                            self.hide=obj.getProperty("hide").getData()
                        except AttributeError:
                            pass
                        try:
                            self.name=obj.getProperty("name").getData()
                        except AttributeError:
                            pass
                        return
                except AttributeError:
                    pass
        #Not Found
        if create:
            if num<0:
                mod=0
            else:
                mod=1
            x=abs(num) % 10
            y=(abs(num)/10) % 10
            z=((abs(num)/100) % 10) + mod
            obj = alcCreateBox("xPage%i" %num,1,x,y,z)
            global splayer
            obj.layers = splayer
            obj.drawType = 2
            #print "adding property page", num
            obj.addProperty("page",int(num))
            self.page=obj
            self.setName("unnamed%i" %num)
            self.setHide(0)
            self.setType(0)
        else:
            self.page=None

    
    def addProp(self,name,val):
        #print "addProp", name, val
        if self.page==None:
            self.find()
        addProp(self.page,name,val)
    
    
    def setName(self,name):
        self.addProp("name",name)
        self.name=name
    
    
    def setHide(self,hide):
        self.addProp("hide",hide)
        self.hide=hide
    
    
    def setType(self,type):
        self.addProp("type",type)
        self.type=type

##    def getFileName(self):
##        base=self.resmanager.getBasePath()
##        agename=self.book.age.name
##        pagename=self.name
##        if self.resmanager.getPRPVersion()==6:
##            return base + "/" + agename + "_" + pagename + ".prp"
##        else:
##            return base + "/" + agename + "_District_" + pagename + ".prp"
##
