from setuptools import Command, setup
from setuptools.command.build_py import build_py as _build
from setuptools.command.sdist import sdist as _sdist
from datetime import datetime


class data(Command):

    description = "Convert the NIST database of constants"
    user_options = []
    boolean_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        with open('quantities/constants/NIST_codata.txt') as f:
            data = f.read()
        data = data.split('\n')[10:-1]

        with open('quantities/constants/_codata.py', 'w') as f:
            f.write('# THIS FILE IS AUTOMATICALLY GENERATED\n')
            f.write('# ANY CHANGES MADE HERE WILL BE LOST\n')
            f.write(f'# LAST GENERATED: {datetime.now()}\n\n')
            f.write('physical_constants = {}\n\n')
            for line in data:
                name = line[:55].rstrip().replace('mag.','magnetic')
                name = name.replace('mom.', 'moment')
                val = line[55:77].replace(' ','').replace('...','')
                prec = line[77:99].replace(' ','').replace('(exact)', '0')
                unit = line[99:].rstrip().replace(' ', '*').replace('^', '**')
                d = "{'value': %s, 'precision': %s, 'units': '%s'}" \
                    %(val, prec, unit)
                f.write("physical_constants['%s'] = %s\n"%(name, d))


class sdist(_sdist):

    def run(self):
        self.run_command('data')
        _sdist.run(self)


class build(_build):

    def run(self):
        self.run_command('data')
        _build.run(self)


setup(cmdclass={"build_py": build, "sdist": sdist, "data": data})
