#!/usr/bin/python3
#   Copyright (C) 2022 John Kacur
"""
Functions to translate a scheduling policy into either a string name or an
equivalent integer
"""
import os

SCHED_POLICIES = {
    "SCHED_OTHER": os.SCHED_OTHER,
    "SCHED_FIFO": os.SCHED_FIFO,
    "SCHED_RR": os.SCHED_RR,
    "SCHED_BATCH": os.SCHED_BATCH,
    "SCHED_IDLE": os.SCHED_IDLE,
    "SCHED_DEADLINE": 6
}


def sched_fromstr(policy):
    """ Given a policy as a string, return the equivalent integer """
    try:
        return SCHED_POLICIES[policy]
    except KeyError as exc:
        raise OSError('No such policy') from exc


def sched_str(policy):
    """ Given a policy as an integer, return the equivalent string name """
    for pstr, pnum in SCHED_POLICIES.items():
        if pnum == policy:
            return pstr
    return "UNKNOWN"

class Policy:
    """ class to encapsulate some scheduling policies operations """

    SCHED_POLICIES = {
        "SCHED_OTHER": os.SCHED_OTHER,
        "SCHED_FIFO": os.SCHED_FIFO,
        "SCHED_RR": os.SCHED_RR,
        "SCHED_BATCH": os.SCHED_BATCH,
        "SCHED_IDLE": os.SCHED_IDLE,
        "SCHED_DEADLINE": 6
    }

    RT_POLICIES = ["SCHED_FIFO", "SCHED_RR"]

    def __init__(self, policy):
        """
        init the class given a policy as a string
        can use fifo, FIFO, sched_fifo, SCHED_FIFO, etc
        """
        self.policy = None
        policy = policy.upper()
        if policy[:6] != "SCHED_":
            policy = "SCHED_" + policy
        if policy not in list(Policy.SCHED_POLICIES):
            raise OSError
        self.policy = policy

    @classmethod
    def num_init(cls, policy):
        """ init the class with an integer corresponding to the policy """
        for pstr, pnum in cls.SCHED_POLICIES.items():
            if policy == pnum:
                return cls(pstr)
        return cls("UNKNOWN")

    def __str__(self):
        """ return the policy in string format """
        return self.policy

    def get_sched(self):
        """ return the policy in string format """
        return self.policy

    def get_short_str(self):
        """ return the policy in string format, without the SCHED_ part """
        return self.policy[6:]

    def get_policy(self):
        """ return the integer equivlent of the policy """
        return SCHED_POLICIES[self.policy]

    def is_rt(self):
        """ Return True if policy is a realtime policy """
        return self.policy in Policy.RT_POLICIES
