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

from ppms import ppms
from ppms.migration import PacketCategory, MaxVersionDependency, VersionType, MinVersionDependency, \
    SQLPacket, ChangeDTPPacket


class AddInterfaceLoggingExport(SQLPacket):
    """Port the customizing for the new interface logging export functionality"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13958

    FILENAME = 'wi13958_export_logging.sql'

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

    def fix(self, runner):
        self.apply_dml_file(self.sql_planta_de_dbms, self.FILENAME)

        return self.success()


class PortOLE1387(ChangeDTPPacket):
    """Port the OLE 001387 to Venus on Earth"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13958

    """
    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5', version_type=VersionType.CUSTOMIZING))
    """

    def fix(self, runner):
        FILES = {'001387': '0040-doc_export.png'}

        errors = 0

        for ident, filename in FILES.items():
            f_path = os.path.join(os.path.dirname(__file__), filename)
            ole_rec = ppms.search_record(31, [ident], [26169], True)

            hl_di = ole_rec.standard_ole
            if not hl_di and not hl_di.is_hyperlink():
                errors += 1

            # Save ole as a hyperlink
            hyperlink = hl_di.get_hyperlink()
            if not hyperlink:
                errors += 1

            with open(f_path, 'rb') as f:
                barray = bytearray(f.read())
                assert hyperlink.set_value(binary=barray, url=filename)
                assert ole_rec.save()

        if errors:
            return self.fail()
        return self.success()