# Taken from course documents. All additions and edits will be noted
from priority_queue_base import PriorityQueueBase

class HeapPriorityQueue(PriorityQueueBase):  # base class defines _Item
    """A min-oriented priority queue implemented with a binary heap."""

    # ------------------------------ nonpublic behaviors ------------------------------
    def _parent(self, j):
        return (j - 1) // 2

    def _left(self, j):
        return 2 * j + 1

    def _right(self, j):
        return 2 * j + 2

    def _has_left(self, j):
        return self._left(j) < len(self._data)  # index beyond end of list?

    def _has_right(self, j):
        return self._right(j) < len(self._data)  # index beyond end of list?

    def _swap(self, i, j):
        """Swap the elements at indices i and j of array."""
        self._data[i], self._data[j] = self._data[j], self._data[i]

    def _upheap(self, j): ### Altered from original, to create max-heap all "<" were changed to ">"
        parent = self._parent(j)
        if j > 0 and self._data[j] > self._data[parent]:
            self._swap(j, parent)
            self._upheap(parent)  # recur at position of parent

    def _downheap(self, j): ### Altered from original, to create max-heap all "<" were changed to ">"
        if self._has_left(j):
            left = self._left(j)
            small_child = left  # although right may be smaller
            if self._has_right(j):
                right = self._right(j)
                if self._data[right] > self._data[left]:
                    small_child = right
            if self._data[small_child] > self._data[j]:
                self._swap(j, small_child)
                self._downheap(small_child)  # recur at position of small child

    # ------------------------------ public behaviors ------------------------------
    def __init__(self):
        """Create a new empty Priority Queue."""
        self._data = []

    def __len__(self):
        """Return the number of items in the priority queue."""
        return len(self._data)

    def add(self, key, value):
        """Add a key-value pair to the priority queue."""
        self._data.append(self._Item(key, value))
        self._upheap(len(self._data) - 1)  # upheap newly added position

    def max(self):  ### Altered from original. min changed to max
        """Return but do not remove (k,v) tuple with minimum key.

        Raise Empty exception if empty.
        """
        if self.is_empty():
            raise Exception('Priority queue is empty.')
        item = self._data[0]
        return (item._key, item._value)

    def remove_max(self): ### Altered from original. min changed to max
        """Remove and return (k,v) tuple with minimum key.

        Raise Empty exception if empty.
        """
        if self.is_empty():
            raise Exception('Priority queue is empty.')
        self._swap(0, len(self._data) - 1)  # put minimum item at the end
        item = self._data.pop()  # and remove it from the list;
        self._downheap(0)  # then fix new root
        return (item._key, item._value)

    def __iter__(self):
        """Generate iteration of the map's keys."""
        for item in self._data:
            yield item  # yield the KEY

# if __name__ == '__main__':
#     H = HeapPriorityQueue()  # Create HeapPriorityQueue[]
#     H.add(0, 'Sue')
#     H.add(5, 'Pat')
#     H.add(6, 'Mark')
#     H.add(7, 'Anna')
#     H.add(9, 'Jeff')
#
#     print(H.max()) # Print out the item with the minimum key
#
#     print('** Show an initial PriorityQueue **')
#     for i in H:
#         print(i)
#
#     print(H.remove_max())
#
#     print('** After running remove_min() **')
#     for i in H:
#         print(i)
#
#     H.add(1, 'Wooky')
#
#     print('** After adding an item, print out minHeap-Priority Queue **')
#     for i in H:
#         print(i)
