import subprocess
from time import sleep

from atonatui.constants import RESET, REVERSE, BOLD, GREEN, RED, BLUE, YELLOW, MAGENTA
from atonatui.settings_mixin import Settings


class DisplayMixin:

    def message(self, msg, callback, sleep_time=1.5, type="ERROR"):
        self.clear_screen()

        color = RED if type == "ERROR" else GREEN
        print(f"{REVERSE}{color}{msg}{RESET}")

        sleep(sleep_time)
        self.clear_screen()

        callback()

    def clear_screen(self):
        subprocess.run(['clear'])

    def display(self, play_mode=False):
        print(f"{GREEN}=================================== ATONATUI ===================================={RESET}\n")

        print(f"{YELLOW}{Settings.BPM} BPM - OCTAVE {Settings.OCTAVE} - {Settings.INSTRUMENT}  {RESET}")
        print(f'{GREEN}{REVERSE}      {BOLD}{" | ".join(f"I{i}".ljust(3) for i in self.inversion)}      {RESET}')

        for row, prime in zip(self.string_matrix, self.prime):
            padded_row = [note.ljust(3) for note in row]
            pr_label = self.reordered_notes.index(row[0])

            if not self.pr_map_populated:
                self.pr_map[f"P{pr_label}"] = row

            print(f'{BOLD}{GREEN}{REVERSE}{f"P{pr_label}".ljust(3)}{RESET} | {" | ".join(padded_row)}|  {BOLD}{GREEN}{REVERSE}{f"R{pr_label}".ljust(3)}{RESET}')

        self.pr_map_populated = True

        if not self.inv_map_populated:
            for idx, i in enumerate(self.inversion):
                new_row = []
                for idx2, row in enumerate(self.matrix):
                    new_row.append(self.reordered_notes[row[idx]])
                self.inv_map[f"I{i}"] = new_row
            self.inv_map_populated = True

        print(f'{GREEN}{REVERSE}      {BOLD}{" | ".join(f"i{i}".ljust(3) for i in self.inversion)}      {RESET}\n')

        if not play_mode:
            print(f"{MAGENTA}{BOLD}{REVERSE}TONE | {' | '.join([i.ljust(3) for i in self.tone_row])}     {RESET}")
            print(f"{YELLOW}{BOLD}{REVERSE}RTHM | {' | '.join([str(x).ljust(3) for x in self.rhythm_row])}     {RESET}")
            print(f"{GREEN}{BOLD}{REVERSE}OCTV | {' | '.join([str(x).ljust(3) for x in self.octave_row])}     {RESET}")

    def loop(self):
        self.clear_screen()
        self.display()

        self.get_user_input()

        self.loop()
