#!/usr/bin/env python3

import os
import re
import sys

ALACRITTY_CONFIG_FILE_NAME = "alacritty.toml"
CONFIG_FILE_DIR = os.path.expanduser("~/.config/alacritty/")
ALACRITTY_CONFIG_FILE_PATH = os.path.join(CONFIG_FILE_DIR, ALACRITTY_CONFIG_FILE_NAME)

COLOR_SCHEME_LINE_SEARCH = r'import = \[.*\]'
ALACRITTY_LIGHT_THEME="solarized_light.toml"
ALACRITTY_DARK_THEME="dark_mode.toml"

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(light_mode=None):
    with open(ALACRITTY_CONFIG_FILE_PATH, "r") as scheme_file:
        scheme_file.seek(0)
        lines = scheme_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:
            colors_line_index = i
            color_line = lines[i]
            break
    
    if light_mode is None:
        if ALACRITTY_DARK_THEME in color_line:
            color_line = color_line.replace(ALACRITTY_DARK_THEME, ALACRITTY_LIGHT_THEME)
            new_scheme = "light"
        else:
            color_line = color_line.replace(ALACRITTY_LIGHT_THEME, ALACRITTY_DARK_THEME)
            new_scheme = "dark"
    elif light_mode == True:
        new_scheme = "light"
        color_line = color_line.replace(ALACRITTY_DARK_THEME, ALACRITTY_LIGHT_THEME)
    else:
        color_line = color_line.replace(ALACRITTY_LIGHT_THEME, ALACRITTY_DARK_THEME)
        new_scheme = "dark"
    lines[colors_line_index] = color_line
    with open(ALACRITTY_CONFIG_FILE_PATH, "w") as scheme_file:
        for line in lines:
            scheme_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(light_mode=None):
    new_theme = change_alacritty_theme(light_mode)
    change_vim_theme(new_theme == "light")
    

if __name__=="__main__":
    if len(sys.argv) == 2:
        main(sys.argv == "light")
    else:
        main()
