#!/usr/bin/env python3

import os
import re


CONFIG_FILE_NAME = "schemes.yml"
CONFIG_FILE_DIR = os.path.expanduser("~/.config/alacritty/")
CONFIG_FILE_PATH = os.path.join(CONFIG_FILE_DIR, CONFIG_FILE_NAME)

COLOR_SCHEME_LINE_SEARCH = "colors: \*(\S+)"
COLOR_SCHEME_LINE_TEMPLATE = "colors: *{}\n"

NVIM_CONFIG_FILE_DIR = os.path.expanduser("~/.config/nvim/")
NVIM_CONFIG_FILE_NAME = "scheme.vim"
NVIM_CONFIG_FILE_PATH = os.path.join(NVIM_CONFIG_FILE_DIR, NVIM_CONFIG_FILE_NAME)

NVIM_COLOR_SCHEME_LINE_SEARCH = "set background=(\S+)\ncolorscheme (\S+)"
NVIM_COLOR_SCHEME_LINE_TEMPLATE = "set background={}\ncolorscheme {}"

def change_alacritty_theme():
    with open(CONFIG_FILE_PATH, "r") as config_file:
        config_file.seek(0)
        lines = config_file.readlines()

    colors_line_index = -1
    for i, line in enumerate(lines):
        match = re.search(COLOR_SCHEME_LINE_SEARCH, line)
        if match is not None:
            current_color_scheme = match.group(1)
            colors_line_index = i


    if current_color_scheme == "dark_mode":
        new_scheme = "solarized_light"
    else:
        new_scheme = "dark_mode"

    lines[colors_line_index] = COLOR_SCHEME_LINE_TEMPLATE.format(
        new_scheme)

    with open(CONFIG_FILE_PATH, "w") as config_file:
        for line in lines:
            config_file.write(line)
    return new_scheme

def change_vim_theme(light_mode=False):
    with open(NVIM_CONFIG_FILE_PATH, "r") as config_file:
        config_file.seek(0)
        config = config_file.read()
    if light_mode:
        color_line = NVIM_COLOR_SCHEME_LINE_TEMPLATE.format("light", "solarized")
    else:
        color_line = NVIM_COLOR_SCHEME_LINE_TEMPLATE.format("dark", "badwolf")
    res = re.sub(NVIM_COLOR_SCHEME_LINE_SEARCH, color_line, config)
    with open(NVIM_CONFIG_FILE_PATH, "w") as config_file:
        config = config_file.write(res)
    

def main():
    new_theme = change_alacritty_theme()
    change_vim_theme(new_theme == "solarized_light")
    

if __name__=="__main__":
    main()
