# -*- coding: utf-8 -*-
import os
import imp

from ppms.migration.packet import *


__all__ = ['CreateFolderPacket']

# Drag these into the local namespace for sake of readability
join = os.path.join
abspath = os.path.abspath

PY_FOLDER = abspath(join('.', 'py'))
CUSTOMER_FOLDER = abspath(join(PY_FOLDER, 'customer'))
PLANTA_DE_FOLDER = abspath(join(PY_FOLDER, 'planta_de'))
PLANTA_CH_FOLDER = abspath(join(PY_FOLDER, 'planta_ch'))
SYSTEM_FOLDER = abspath(join(PY_FOLDER, 'system'))

SUFFIXES = imp.get_suffixes()
POSSIBLE_INIT_FILES = ['__init__%s' % suffix[0] for suffix in imp.get_suffixes()]

IMPORT_STMT_PLANTA_DE = '''# This file is generated automatically, edit only the correspondent file in the customer directory
try:
    from planta_de{fname} import *
except ImportError:
    raise ImportError('Importing * from planta_de{fname} failed, please check your installation')

try:
    from planta_ch{fname} import *
except ImportError:
    pass

try:
    from customer{fname} import *
except ImportError:
    pass
'''

IMPORT_STMT_CUSTOMER = '''# This file is generated automatically, edit only the correspondent file in the customer directory
try:
    from customer{fname} import *
except ImportError:
    raise ImportError('Importing * from customer{fname} failed, please check your installation')
'''


class CreateFolderPacket(BasePacket):
    '''Create the full Venus folder structure based on a planta_de folder.

    1) Walk down /py/planta_de and create the corresponding
       planta_ch/customer/system folders.
    2) Walk down /py/customer and generate wrappers inside /py/system for
       customer-only files
    '''

    wi_number = 10294
    version = 1
    done_after_success = False
    run_on_startup = True
    category = PacketCategory.CATEGORY_HELPER

    def fix(self, runner):
        try:
            self.create_folder_structure()
            self.create_customer_wrappers_in_system()
        except OSError as err:
            self.fail(err)

        return self.success()

    def create_folder_structure(self):
        self.log_heading('WALKING PLANTA_DE FOLDER')
        self.log('Walking "%s" for python packages' % PLANTA_DE_FOLDER)
        for dirpath, dirnames, filenames in os.walk(PLANTA_DE_FOLDER):
            if '__pycache__' in dirnames:
                dirnames.remove('__pycache__')

            is_package = [i for i in POSSIBLE_INIT_FILES if i in filenames]

            if not is_package:
                self.log('Skipping "%s" - not a python package' % abspath(dirpath))
                continue

            else:
                self.log('Traversing "%s"' % abspath(dirpath))

            for folder in (CUSTOMER_FOLDER, PLANTA_CH_FOLDER, SYSTEM_FOLDER):
                new_dirpath = dirpath.replace(PLANTA_DE_FOLDER, folder)

                if not os.path.isdir(new_dirpath):
                    self.log('Creating folder "%s"' % new_dirpath)
                    os.makedirs(new_dirpath)

                    if folder == SYSTEM_FOLDER:
                        for name in filenames:
                            fname = new_dirpath.replace(SYSTEM_FOLDER, '').replace(os.sep, '.') + '.' + os.path.splitext(name)[0]
                            stmt = IMPORT_STMT_PLANTA_DE.format(**locals())
                            fpath = join(new_dirpath, name)

                            self.log('Creating import wrapper at "%s"' % fpath)
                            with open(fpath, 'w') as f:
                                f.write(stmt)
                    else:
                        fpath = join(new_dirpath, '__init__.py')

                        if os.path.isfile(fpath):
                            self.log('"%s" already exists - skipping' % fpath)
                            continue

                        self.log('Creating a dummy __init__.py')
                        with open(fpath, 'w') as f:
                            pass

    def create_customer_wrappers_in_system(self):
        self.log_heading('WALKING CUSTOMER FOLDER')
        self.log('Walking "%s" for python packages' % CUSTOMER_FOLDER)
        for dirpath, dirnames, filenames in os.walk(CUSTOMER_FOLDER):
            if '__pycache__' in dirnames:
                dirnames.remove('__pycache__')

            is_package = [i for i in POSSIBLE_INIT_FILES if i in filenames]

            if not is_package:
                self.log('Skipping "%s" - not a python package' % abspath(dirpath))
                continue

            else:
                self.log('Traversing "%s"' % abspath(dirpath))

            new_dirpath = dirpath.replace(CUSTOMER_FOLDER, SYSTEM_FOLDER)
            if os.path.isdir(new_dirpath):
                self.log('Looking at files: %s' % filenames)
                for name in filenames:
                    fname = new_dirpath.replace(SYSTEM_FOLDER, '').replace(os.sep, '.') + '.' + os.path.splitext(name)[0]
                    fpath = join(new_dirpath, name)

                    if os.path.isfile(fpath):
                        self.log('"%s" already exists - skipping' % fpath)
                        continue

                    self.log('Creating customer individual import wrapper at "%s"' % fpath)
                    with open(fpath, 'w') as f:
                        stmt = IMPORT_STMT_CUSTOMER.format(**locals)
                        f.write(stmt)
            else:
                self.log('Creating folder "%s"' % new_dirpath)
                os.makedirs(new_dirpath)

                fpath = join(new_dirpath, '__init__.py')

                self.log('Creating a dummy __init__.py')
                with open(fpath, 'w') as f:
                    pass
