# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import os
from typing import List

from ..utils.io import read_json, write_json
from ..constants import config_file


class Database:
    """
    Manage most recent brushes and colors.
    """
    def __init__(self):
        self.most_recent_brushes = [] # type: List[str]
        self.favourite_brushes = [] # type: List[str]
        self.favourites_file = config_file('favourites.json')
        if os.path.exists(self.favourites_file):
            self.favourite_brushes = read_json(self.favourites_file).get('brushes', list())


    def get_most_recent_brushes(self) -> List[str]:
        return self.most_recent_brushes


    def add_most_recent_brush(self, bin_hash: str):
        """
        Add bin hash to front of most recent brushes, remove double entry.
        """
        if bin_hash in self.most_recent_brushes:
            self.most_recent_brushes.remove(bin_hash)
        self.most_recent_brushes.insert(0, bin_hash)
        while len(self.most_recent_brushes) > 8:
            self.most_recent_brushes.pop()


    def get_favourite_brushes(self) -> List[str]:
        return self.favourite_brushes


    def __save_favourites_file(self):
        write_json(
            self.favourites_file, 
            { 'brushes': self.favourite_brushes }
        )


    def add_favourite_brush(self, bin_hash: str):
        """
        Add bin hash to front of favourite brushes, remove double entry.
        """
        if bin_hash in self.favourite_brushes:
            self.favourite_brushes.remove(bin_hash)
        self.favourite_brushes.insert(0, bin_hash)
        while len(self.favourite_brushes) > 8:
            self.favourite_brushes.pop()      
        self.__save_favourites_file()


    def rem_favourite_brush(self, bin_hash: str):
        """
        Remove bin hash from favourite brushes.
        """
        if bin_hash in self.favourite_brushes:
            self.favourite_brushes.remove(bin_hash)
        self.__save_favourites_file()


    @staticmethod
    def instance() -> 'Database':
        """
        Access as singleton.
        """
        global _instance
        return _instance


_instance = Database()    
