from __future__ import annotations

import re
from shutil import copyfile
from pathlib import Path
import os
from configparser import ConfigParser
from importlib.resources import path as resource_path

from nmreval.configs import config_paths
from nmreval.lib.logger import logger


def make_starter(app_file: str | None):
    if app_file is not None:
        make_starter_appimage(Path(app_file))
    else:
        make_starter_src()


def make_starter_appimage(app_file: Path):
    new_path = Path.home() / '.local' / 'bin'

    if not new_path.exists():
        new_path.mkdir(parents=True)

    new_path /= app_file.name

    if app_file != new_path:
        app_file.rename(new_path)

    create_desktop_file(new_path)


def make_starter_src():
    home = Path.home()
    p = Path.home()
    for p in Path(__file__).parents:
        if p.stem == 'src':
            break
        elif p == home:
            break

    success = p != Path.home()
    if success:
        bin_path = p.with_name('bin') / 'evaluate.py'
        success = bin_path.exists()

    if not success:
        logger.warning('Location of evaluate.py could not be determined')
        return False

    create_desktop_file(bin_path)


def create_desktop_file(new_path: Path):
    logo_path = config_paths() / 'logo.png'
    if not logo_path.exists():
        with resource_path('resources', 'logo.png') as fp:
            copyfile(fp, logo_path)
    desktop_entry = f"""\
[Desktop Entry]
Name=NMReval
Comment=Best program ever (maybe)
Exec={new_path}
Icon={logo_path}
Type=Application
Terminal=false
Categories=Science;NumericalAnalysis;Physics;DataVisualization;Other;
NoDisplay=false
"""
    file_name = 'pkm.vogel.nmreval.desktop'
    with Path('~/.local/share/applications/', file_name).expanduser().open('w') as f:
        f.write(desktop_entry)

    desktop_dir = get_xkg_user_dirs('desktop')
    if desktop_dir is not None:
        desk_file = Path(desktop_dir, file_name)
        with desk_file.open('w') as f:
            f.write(desktop_entry)

        desk_file.chmod(0o755)


def get_xkg_user_dirs(dir_type: str) -> str | None:
    xdg_conf_home = os.getenv('XDG_CONFIG_HOME') or str(Path.home() / '.config')

    with Path(xdg_conf_home, 'user-dirs.dirs').open('r') as f:
        conf_string = '[XDG_USER_DIRS]\n' + f.read()
        conf_string = re.sub(r'\$HOME', str(Path.home()), conf_string)
        conf_string = re.sub('"', '', conf_string)

    config = ConfigParser()
    config.read_string(conf_string)

    return config['XDG_USER_DIRS'].get(f'xdg_{dir_type}_dir')


if __name__ == '__main__':
    make_starter()
