from ..generator import Generator

import os
import sys


class JamfileGenerator(Generator):
    @staticmethod
    def identifier():
        return 'jamfile'

    def generate(self, needy):
        path = os.path.join(needy.needs_directory(), 'Jamfile')
        contents = """import feature ;
import toolset ;

path-constant NEEDY : %s ;
path-constant BASE_DIR : %s ;
path-constant NEEDS_FILE : %s ;

rule needlib ( name : extra-sources * : requirements * : default-build * : usage-requirements * )
{
    local builddir = [ SHELL "cd $(BASE_DIR) && $(NEEDY) builddir $(name)" ] ;

    feature.feature needyargs : : free ;
    toolset.flags $(__name__).satisfy-lib NEEDYARGS <needyargs> ;

    make lib$(name).touch : $(NEEDS_FILE) : @satisfy-lib : <needyargs>$(name) ;
    actions satisfy-lib
    {
        cd $(BASE_DIR) && $(NEEDY) satisfy $(NEEDYARGS)
    }

    alias $(name)
        : $(extra-sources) 
        : $(requirements) 
        : $(default-build) 
        : <dependency>lib$(name).touch
          <include>$(builddir)/include
          <linkflags>-L$(builddir)/lib
          $(usage-requirements)
    ;
}

""" % (os.path.abspath(sys.argv[0]), os.path.dirname(needy.path()), needy.path())

        for library in needy.libraries_to_build():
            contents += 'needlib {} ;\n'.format(library[0])

        with open(path, 'w') as jamfile:
            jamfile.write(contents)

@@ -394,16 +394,116 @@
 : %25s ;%0A%0A
+feature.feature needyargs : : free ;%0Atoolset.flags $(__name__).satisfy-lib NEEDYARGS %3Cneedyargs%3E ;%0A%0A
 rule nee
@@ -608,182 +608,408 @@
 cal 
-builddir = %5B SHELL %22cd $(BASE_DIR) && $(NEEDY) builddir $(name)%22 %5D ;%0A%0A    feature.feature needyargs : : free ;%0A    toolset.flags $(__name__).satisfy-lib NEEDYARGS %3Cneedyargs%3E
+target = $(name) ;%0A    %0A    if %3Ctarget-os%3Eiphone in $(requirements) %7B%0A        target = %22$(name) -u iphone%22 ;%0A    %7D else if %3Ctarget-os%3Eandroid in $(requirements) %7B%0A        target = %22$(name) -t android:armv7%22 ;%0A    %7D else if %3Ctarget-os%3Easappletv in $(requirements) %7B%0A        target = %22$(name) -t appletv:arm64%22 ;%0A    %7D%0A    %0A    local builddir = %5B SHELL %22cd $(BASE_DIR) && $(NEEDY) builddir $(target)%22 %5D
  ;%0A%0A
@@ -1066,16 +1066,32 @@
 fy-lib :
+ $(requirements)
  %3Cneedya
@@ -1096,20 +1096,22 @@
 yargs%3E$(
-name
+target
 ) ;%0A    
@@ -1150,35 +1150,40 @@
   cd $(BASE_DIR)
- &&
+%0A       
  $(NEEDY) satisf
@@ -1197,16 +1197,48 @@
 DYARGS)%0A
+        cd -%0A        touch $(%3C)%0A
     %7D%0A%0A 
@@ -1494,17 +1494,16 @@
     ;%0A%7D%0A
-%0A
 %22%22%22 %25 (o
@@ -1652,17 +1652,20 @@
 ents += 
-'
+%22%22%22%0A
 needlib 
@@ -1669,14 +1669,126 @@
 ib %7B
+0
 %7D ;
-%5Cn'
+%0Aneedlib %7B0%7D : : %3Ctarget-os%3Eiphone ;%0Aneedlib %7B0%7D : : %3Ctarget-os%3Eandroid ;%0Aneedlib %7B0%7D : : %3Ctarget-os%3Eappletv ;%0A%22%22%22
 .for

add iphone, android, appletv support to jamfile generator