# -*- coding: utf-8 -*-
import re

from ppms.migration import DeprecatedPythonPacket, PacketCategory, MaxVersionDependency, VersionType
from csrpc.utils import access


class FindExecInCustomerDirectory(DeprecatedPythonPacket):
    """Find every usage of client_exec/server_exec in the customer directories.
    
    Note: This migration packet needs to be executed from a client
    which was stated from either the planta.exe or from a link to the planta.exe.

    If the migration packet is executed from a client started via a *.bat file or similar,
    it won't be able to search through the client customer folders.
    """
    run_on_startup = False
    done_after_success = True
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 15191

    def get_dependencies(self):
        return (MaxVersionDependency(version='39.5.7', version_type=VersionType.CUSTOMIZING))

    def search_client_directory(self):
        found_occurrence = False

        if access.service_is_available('search_handler'):
            search_handler = access.remote_service('search_handler')
            for path in (('Lib', 'Earth', 'customer'), ('Lib', 'Main', 'customer')):
                client_path = search_handler.make_client_path(*path)

                server_exec_occurrences = search_handler.search_python_files_for_string(client_path, 'server_exec')
                for file_path, line_numbers in server_exec_occurrences:
                    self.log_heading('SERVER EXEC IN "%s" ' % file_path)
                    self.log('Found server_exec at the following line numbers: %s' % ', '.join(line_numbers))

                    found_occurrence = True

                client_exec_occurrences = search_handler.search_python_files_for_string(client_path, 'client_exec')
                for file_path, line_numbers in client_exec_occurrences:
                    self.log_heading('CLIENT EXEC IN "%s" ' % file_path)
                    self.log('Found client_exec at the following line numbers: %s' % ', '.join(line_numbers))

                    found_occurrence = True
        else:
            self.log('Services are not supported by the client, can not search in client directory!')
            found_occurrence = True

        return found_occurrence

    def fix(self, runner):
        self.log_heading('Looking at the client directory')
        fail = self.search_client_directory()

        self.log_heading('Looking at the server directory')
        counter = self.search_for_code()

        if fail or counter > 0:
            return self.fail('System isn\'t clean yet!')

        return self.success()

    def get_matching_objects(self, iterable_to_filter):
        search = lambda x: re.search('(client_exec)|(server_exec)', x.source)

        return list(filter(search, iterable_to_filter))
