#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
"""
    Module pyant
    ant by python
"""
import os, sys
import os.path
from distutils.core import setup
import distutils
try:
    from setuptools import setup, find_packages 
    pip_available = True
except:
    pip_available = False
import pyant
from mytools.util import *
 
class PipTask(pyant.Task):
    """
    execute of pip compilation
 
    name of element : **pip**
 
    ==================== ============================================= ========
    Attribute            Information                                   Required
    ==================== ============================================= ========
    action               default install (separated by ;)
    failonerror          stop if failure default true 
    ==================== ============================================= ========
 
    You can use element param for add parameter of compilation or add import
    module (param with name import)
    """
 
    ATTR_REQUIRED = []
    ATTR_DEFAULT = {'action' : 'install',
                    'failonerror' : 'true'}
    ATTR_POSSIBLE_VALUE = {'failonerror' : ['true','false'] } 
 
    def __init__(self, **kwargs):
        pyant.Task.__init__(self, **kwargs)
        self.myparam = []
        self.myimport = []
 
    def _checkadd(self):
        if 'Param' in self._append_obj.keys():
            for i in self._append_obj['Param']:
                if i.name != 'import':
                    self.myparam.append(i)
                else:
                    self.myimport.append(i.get())
 
    def _run(self):
        try:
            for i in self.myimport:
                self.log('DEBUG','import %s' % i)
                pyant.import_global(i)
            param = { i.name : i.get() for i in self.myparam}
            distutils.core._setup_stop_after = "config" #no manage command_line
            for i in param:
                self.log('DEBUG', '%s : %s' % (i, param[i]))
            dist = setup(**param)
            for i in self._action.split(';'):
                dist.run_command(i)
            self.log('INFO','pip setup %s' % self._action)
        except Exception as e:
            if self._failonerror == 'false':
                self.log('DEBUG','error on pip %s' % self._action)
            else:
                raise e
 
if pip_available:
    pyant.ANTCLASS['pip'] = PipTask