#!/usr/bin/env python3
#
#       Ferit Yiğit BALABAN <fyb@duck.com>, 2022
#
#       fetchpy, fetch script alternative to neofetch
import os
from subprocess import run


IMG_LOC = '/home/ferit/shoka/500-599 pictures/505 clipart/windowschan_s.png'


def clr(text: str):
    dump = '\u001b[30m█\u001b[31m█\u001b[32m█\u001b[33m█\u001b[34m█\u001b[35m█\u001b[36m█\u001b[37m█'
    frame = '\u001b[31m' 
    info = '\u001b[32m'
    title = '\u001b[33m'
    clr_dict = {
        '╭': frame,
        '╰': frame,
        '╯': frame,
        '─': frame,
        '╮': frame,
        '┤': frame,
        '│': frame,
        '├': frame,
        '': info,
        '': info,
        '': info,
        '': info,
        '': info,
        '󰢮': info,
        '': info,
        '': info,
        'ferit@navi': title,
        'Hardware': '',
    }
    iter = 0
    while iter < len(text):
        char = text[iter]
        peekable = iter < len(text) - 1
        peek = text[iter + 1] if peekable else ' '

        if char == ' ':
            if peekable and peek != ' ' and not clr_dict.__contains__(peek):
                print(' ', end='')
                word, jump_to = read_until_space(text, start_at=iter + 1)
                if clr_dict.__contains__(word):
                    if word == 'Hardware':
                        print(dump, end='')
                    else:
                        print(f'{clr_dict[word]}{word}\u001b[0m', end='')
                else:
                    print(word, end='')
                iter = jump_to
            print(' ', end='')
        elif clr_dict.__contains__(char):
            print(f'{clr_dict[char]}{char}\u001b[0m', end='')
        else:
            print(char, end='')
        iter += 1
    print('')


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


def main():
    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 = 16
    line_count = 0 
    for line in txt.splitlines():
        txt_padded += ((' ' * img_width) + line + '\n')
        line_count += 1
    print('')
    run(['/usr/bin/kitty', 'icat', '--mirror', 'horizontal', '--align', 'left', IMG_LOC])
    run(['printf', "\e[%sA\e[999999D", str(line_count)])
    clr(txt_padded)


if __name__ == '__main__':
    main()

