from setuptools import setup, Command
import site
import os
import platform




class Reusing(Command):
    description = "Fetch remote modules"
    user_options = [
      # The format is (long option, short option, description).
      ( 'local', None, 'Update files without internet'),
  ]

    def initialize_options(self):
        self.local=False

    def finalize_options(self):
        pass

    def run(self):
        from sys import path
        path.append("unogenerator/reusing")
        print(self.local)
        if self.local is False:
            from github import download_from_github
            download_from_github('turulomio','reusingcode','python/github.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/casts.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/datetime_functions.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/listdict_functions.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/file_functions.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/decorators.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/libmanagers.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/percentage.py', 'unogenerator/reusing/')
            download_from_github('turulomio','reusingcode','python/currency.py', 'unogenerator/reusing/')
        
        from file_functions import replace_in_file
        replace_in_file("unogenerator/reusing/casts.py","from currency","from unogenerator.reusing.currency")
        replace_in_file("unogenerator/reusing/casts.py","from percentage","from unogenerator.reusing.percentage")
        replace_in_file("unogenerator/reusing/listdict_functions.py","from casts","from unogenerator.reusing.casts")


## Class to define doc command
class Translate(Command):
    description = "Update translations"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        #es
        os.system("xgettext -L Python --no-wrap --no-location --from-code='UTF-8' -o locale/unogenerator.pot *.py unogenerator/*.py unogenerator/reusing/*.py setup.py")
        os.system("msgmerge -N --no-wrap -U locale/es.po locale/unogenerator.pot")
        os.system("msgfmt -cv -o unogenerator/locale/es/LC_MESSAGES/unogenerator.mo locale/es.po")
        os.system("msgfmt -cv -o unogenerator/locale/en/LC_MESSAGES/unogenerator.mo locale/en.po")

    
## Class to define doc command
class Documentation(Command):
    description = "Generate documentation for distribution"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        os.system("unogenerator_demo --create")
        os.system("cp -f unogenerator_documentation_en.odt doc/")
        os.system("cp -f unogenerator_documentation_en.pdf doc/")
        os.system("cp -f unogenerator_documentation_es.odt doc/")
        os.system("cp -f unogenerator_documentation_es.pdf doc/")
        os.system("cp -f unogenerator_example_en.ods doc/")
        os.system("cp -f unogenerator_example_en.pdf doc/")
        os.system("cp -f unogenerator_example_es.ods doc/")
        os.system("cp -f unogenerator_example_es.pdf doc/")
        os.system("unogenerator_demo --remove")

class Procedure(Command):
    description = "Show release procedure"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        print("""Nueva versión:
  * Cambiar la versión y la fecha en commons.py
  * Modificar el Changelog en README
  * python setup.py translate
  * linguist
  * python setup.py translate
  * python setup.py uninstall; python setup.py install
  * python setup.py documentation
  * python setup.py doxygen
  * git commit -a -m 'unogenerator-{0}'
  * git push
  * Hacer un nuevo tag en GitHub
  * python setup.py sdist
  * twine upload dist/unogenerator-{0}.tar.gz 
  * python setup.py uninstall
  * Crea un nuevo ebuild de UNOGENERATOR Gentoo con la nueva versión
  * Subelo al repositorio del portage

""".format(__version__))

## Class to define doxygen command
class Doxygen(Command):
    description = "Create/update doxygen documentation in doc/html"

    user_options = [
      # The format is (long option, short option, description).
      ( 'user=', None, 'Remote ssh user'),
      ( 'directory=', None, 'Remote ssh path'),
      ( 'port=', None, 'Remote ssh port'),
      ( 'server=', None, 'Remote ssh server'),
  ]

    def initialize_options(self):
        self.user="root"
        self.directory="/var/www/html/doxygen/unogenerator/"
        self.port=22
        self.server="127.0.0.1"

    def finalize_options(self):
        pass

    def run(self):
        print("Creating Doxygen Documentation")
        os.system("""sed -i -e "41d" doc/Doxyfile""")#Delete line 41
        os.system("""sed -i -e "41iPROJECT_NUMBER         = {}" doc/Doxyfile""".format(__version__))#Insert line 41
        os.system("rm -Rf build")
        os.chdir("doc")
        os.system("doxygen Doxyfile")      
        command=f"""rsync -avzP -e 'ssh -l {self.user} -p {self.port} ' html/ {self.server}:{self.directory} --delete-after"""
        print(command)
        os.system(command)
        os.chdir("..")
  
## Class to define uninstall command
class Uninstall(Command):
    description = "Uninstall installed files with install"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        if platform.system()=="Linux":
            os.system("rm -Rf {}/unogenerator*".format(site.getsitepackages()[0]))
            os.system("rm /usr/bin/unogenerator*")
        else:
            os.system("pip uninstall unogenerator")

########################################################################

## Version of unogenerator captured from commons to avoid problems with package dependencies
__version__= None
with open('unogenerator/commons.py', encoding='utf-8') as f:
    for line in f.readlines():
        if line.find("__version__ =")!=-1:
            __version__=line.split("'")[1]


setup(name='unogenerator',
     version=__version__,
     description='Python module to read and write LibreOffice and MS Office files using uno API',
     long_description='Project web page is in https://github.com/turulomio/unogenerator',
     long_description_content_type='text/markdown',
     classifiers=['Development Status :: 4 - Beta',
                  'Intended Audience :: Developers',
                  'Topic :: Software Development :: Build Tools',
                  'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
                  'Programming Language :: Python :: 3',
                 ], 
     keywords='office generator uno pyuno libreoffice',
     url='https://github.com/turulomio/unogenerator',
     author='Turulomio',
     author_email='turulomio@yahoo.es',
     license='GPL-3',
     packages=['unogenerator'],
     install_requires=["tqdm", "humanize", "colorama","polib", "psutil", "pytz"],
     entry_points = {'console_scripts': [
                            'unogenerator_demo=unogenerator.demo:main',
                            'unogenerator_demo_concurrent=unogenerator.demo:main_concurrent',
                            'unogenerator_start=unogenerator.server:server_start',
                            'unogenerator_stop=unogenerator.server:server_stop',
                            'unogenerator_monitor=unogenerator.server:monitor',
                            'unogenerator_translation=unogenerator.translation:main',
                        ],
                    },
     cmdclass={'doxygen': Doxygen,
               'uninstall':Uninstall, 
               'translate': Translate,
               'documentation': Documentation,
               'procedure': Procedure,
               'reusing': Reusing,
              },
     zip_safe=False,
     test_suite = 'unogenerator.tests',
     include_package_data=True
)
