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

from ppms.constants import *
from ppms.migration import SQLPacket, PacketCategory, MaxVersionDependency, VersionType


class AddViewsForScheduler(SQLPacket):
    """Add new views for the scheduling component"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 21328

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

    def add_views(self, folder):
        errors = 0

        for filename in os.listdir(folder):
            file_path = os.path.join(folder, filename)
            filename_no_extension = os.path.splitext(filename)[0]

            if self.view_exists(view_name=filename_no_extension):
                self.log('There is already a view with the name "{}"'.format(filename_no_extension))
                errors += 1
                continue

            with open(file_path, 'r') as f:
                content = f.read()

            self.modify_and_log(query=content, log_rows=False)

        return errors

    def fix(self, packet_runner):
        this_folder = os.path.dirname(os.path.realpath(__file__))
        view_folder = os.path.join(this_folder, 'views')

        if self.DBMS == DBMS_ORACLE:
            dbms_folder = 'oracle'
        elif self.DBMS == DBMS_MSSQL:
            dbms_folder = 'mssql'
        else:
            return self.fail('Invalid dbms: {}'.format(self.DBMS))

        dbms_specific_folder = os.path.join(view_folder, dbms_folder)
        errors = self.add_views(dbms_specific_folder)

        if errors:
            return self.fail('Not all views could be created!')
        else:
            self.log('All views created successfully')

        return self.success()
