#!/usr/bin/env python3
#
#       Ferit Yiğit BALABAN <fyb@duck.com>, 2022
#
#       fetchpy, fetch script alternative to neofetch
import os
from subprocess import run
from rich.console import Console
from rich.traceback import install
install(show_locals=True)


COLOR1 = '#75FDFF'
COLOR2 = '#FFE252'
COLOR3 = '#D66565'
COLOR4 = '#FFAB3D'


def read_theme():
    with open('/home/ferit/scripts/fetch.theme', 'r') as f:
        l = f.readlines()
        f.close()
    global COLOR1
    global COLOR2
    global COLOR3
    global COLOR4
    COLOR1 = l[0]
    COLOR2 = l[1]
    COLOR3 = l[2]
    COLOR4 = l[3]


def coloring(text):
    frame = COLOR2
    info = COLOR3
    title = COLOR1
    color_dictionary = {
        '╭': frame,
        '╰': frame,
        '╯': frame,
        '─': frame,
        '╮': frame,
        '┤': frame,
        '│': frame,
        '├': frame,
        '': info,
        '': info,
        '': info,
        '': info,
        '': info,
        '': info,
        '': info,
        '': info,
        '─ferit@navi': title,
        'Hardware': title,
    }
    c = Console()
    iterator = 0
    while iterator < len(text):
        character = text[iterator]
        peekable = iterator < len(text) - 1
        peek = text[iterator + 1] if peekable else ' '

        if character == ' ':
            if peekable and peek != ' ' and not color_dictionary.__contains__(peek):
                print(' ', end='')
                word, jump_to = read_until_space(text, start_at=iterator + 1)
                if color_dictionary.__contains__(word):
                    if '\\' in word:
                        word_style = color_dictionary[word]
                        for character in word:
                            c.print(character, style=word_style, end='')
                    else:
                        c.print(f'[{color_dictionary[word]}]{word}[/{color_dictionary[word]}]', end='')
                else:
                    print(word, end='')
                iterator = jump_to
            print(' ', end='')
        elif color_dictionary.__contains__(character):
            if character == '\\':
                c.print(character, style=color_dictionary[character], end='')
            else:
                c.print(f'[{color_dictionary[character]}]{character}[/{color_dictionary[character]}]', end='')
        else:
            print(character, end='')
        iterator += 1
    print('')


def read_until_space(text, start_at):
    buffer = ''
    iterator = start_at
    while text[iterator] != ' ':
        buffer += text[iterator]
        iterator += 1
    next_space_at = iterator
    return buffer, next_space_at


def main():
    read_theme()
    padding_count = 23

    distro_name = 'Arch GNU/Linux'
    distro_name = distro_name.ljust(padding_count, ' ')

    kernel_version = str(os.uname().release)
    kernel_version = kernel_version.ljust(padding_count, ' ')

    installed_packages = run(['pacman', '-Q'], text=True, capture_output=True).stdout.splitlines()
    shell_name = 'fish'
    for _ in installed_packages:
        if shell_name in _:
            shell_name = _.removesuffix('\n').ljust(padding_count, ' ')
    package_count = str(len(installed_packages)).ljust(padding_count, ' ')

    total_memory, used_memory, free_memory, d1, d2, d3 = map(int, os.popen('free -m').readlines()[1].split()[1:])
    memory_usage = f'{round((used_memory / 1024), 1)} GB / {round((total_memory / 1024), 1)} GB'.ljust(padding_count, ' ')

    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        f.close()
    if uptime_seconds < 60:
        uptime = str(uptime_seconds).split('.')[0] + ' seconds'
    elif uptime_seconds < 3600:
        number = str(uptime_seconds / 60).split('.')[0]
        uptime = f'{number} minute' if number == '1' else f'{number} minutes'
    else:
        number = str(uptime_seconds / 3600).split('.')[0]
        uptime = f'{number} hour' if number == '1' else f'{number} hours'
    uptime = uptime.ljust(padding_count, ' ')

    txt = f'''╭─────── ferit@navi ───────╮
│  {distro_name}│
│  {kernel_version}│
│  {shell_name}│
│  {package_count}│
├──────── Hardware ────────┤
│  AMD Ryzen 7 5800H      │
│  NV GeForce RTX3050 Ti  │
│  {memory_usage}│
│  {uptime}│
╰──────────────────────────╯
'''
    txt_padded = ''
    img_width = 15
    for line in txt.splitlines():
        txt_padded += ((' ' * img_width) + line + '\n')
    coloring(txt_padded)


if __name__ == '__main__':
    main()

