# -*- coding: utf-8 -*-
import hql
from ppms.constants import PLANTA_LICENSES
from ppms.migration import SQLPacket, PacketCategory


class DeleteLinkData(SQLPacket):
    """Delete PLANTA Link data that doesn't belong in the system"""
    done_after_success = False
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 18945

    def entity_exists_in_system(self, entity_name):
        query = """SELECT
                     count(1)
                   FROM
                     DataTable
                   WHERE
                     entityname = '{entity_name}'"""

        try:
            return bool(hql.query(query.format(entity_name=entity_name))[0][0])
        except IndexError:
            return False

    def delete_orphaned_logging_entries(self):
        query = """DELETE
                     Logging
                   WHERE
                     config_id NOT IN (SELECT id FROM InterfaceConfiguration)"""
        return hql.modify(query)

    def delete_orphaned_pool_data(self, entity_name):
        if not self.entity_exists_in_system(entity_name=entity_name):
            return 0

        query = """DELETE
                     {entity_name}
                   WHERE
                     own_lic in {planta_licenses}
                     config_id NOT IN (SELECT id FROM InterfaceConfiguration)"""
        return hql.modify(query.format(entity_name=entity_name, planta_licenses=str(PLANTA_LICENSES)))

    def fix(self, packet_runner):
        self.log('Removed %d orphaned logging entries' % self.delete_orphaned_logging_entries())
        self.log('Removed %d orphaned load pool entries' % self.delete_orphaned_pool_data(entity_name='LoadDataPool'))
        self.log('Removed %d orphaned employee pool entries' % self.delete_orphaned_pool_data(
            entity_name='EmployeePool'))
        self.log('Removed %d orphaned project pool entries' % self.delete_orphaned_pool_data(
            entity_name='ProjectPool'))
        self.log('Removed %d orphaned SAP pool entries' % self.delete_orphaned_pool_data(
            entity_name='SAPProjectstructurePool'))

        return self.success()
