# Steal from https://github.com/noctuid/dotfiles/blob/master/browsing/.config/qutebrowser/config.py

from qutebrowser.config.configfiles import (
    ConfigAPI,
)  # noqa: F401,E501 pylint: disable=unused-import
from qutebrowser.config.config import ConfigContainer  # noqa: F401

config: ConfigAPI = config  # pylint: disable=E0601
c: ConfigContainer = c  # pylint: disable=E0601

config.load_autoconfig(False)


# * Helper Functions
def bind(key, command, mode):  # noqa: E302
    """Bind key to command in mode."""
    # TODO set force; doesn't exist yet
    config.bind(key, command, mode=mode)


def nmap(key, command):
    """Bind key to command in normal mode."""
    bind(key, command, "normal")


def imap(key, command):
    """Bind key to command in insert mode."""
    bind(key, command, "insert")


def cmap(key, command):
    """Bind key to command in command mode."""
    bind(key, command, "command")


# def cimap(key, command):
#     """Bind key to command in command mode and insert mode."""
#     cmap(key, command)
#     imap(key, command)


def tmap(key, command):
    """Bind key to command in caret mode."""
    bind(key, command, "caret")


def pmap(key, command):
    """Bind key to command in passthrough mode."""
    bind(key, command, "passthrough")


def unmap(key, mode):
    """Unbind key in mode."""
    config.unbind(key, mode=mode)


def nunmap(key):
    """Unbind key in normal mode."""
    unmap(key, mode="normal")


# ** Session
# always restore opened sites when opening qutebrowser
c.auto_save.session = True
# Default is 15 secs. Save every 1 min.
c.auto_save.interval = 60000
# Load restored tab as soon as it takes focus
c.session.lazy_restore = True

# ** Tabs
# open new tabs (middleclick/ctrl+click) in the background
c.tabs.background = True
# select previous tab instead of next tab when deleting current tab
c.tabs.select_on_remove = "prev"
# open unrelated tabs after the current tab not last
c.tabs.new_position.related = "next"
c.tabs.new_position.unrelated = "last"
c.tabs.min_width = 100
# Do not wrap when changing tabs
c.tabs.wrap = False
c.tabs.mousewheel_switching = False

c.tabs.title.format = "{index}{private}{title_sep}{current_title}"

# ** Command Aliases
c.aliases["xa"] = "quit --save"
c.aliases["h"] = "help"

# ** Appearance
# Preferred fonts
c.fonts.default_family = [
    "monospace",
]
c.fonts.default_size = "20pt"
c.fonts.tabs.selected = "22pt default_family"
# Spell checking
c.spellcheck.languages = ["en-GB"]

# default but not transparent
c.colors.hints.bg = (
    "qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(255, 247, 133, 1), "
    + "stop:1 rgba(255, 197, 66, 1))"
)

c.scrolling.bar = "always"
c.scrolling.smooth = False

# lower delay for key hint dialog (comparable to which-key)
c.keyhint.delay = 250

c.tabs.padding = {"top": 2, "bottom": 2, "left": 0, "right": 4}

# ** Editor
c.editor.command = ["foot", "nvim", "+{line}", "{}"]

# ** Hints
# don't require enter after hint keys
c.hints.auto_follow = "always"
# As per Colemak mod-dh
c.hints.chars = "arstgmneiowfpluy"

# ** Downloads
c.downloads.location.directory = "~/Downloads/qutebrowser"
c.downloads.location.prompt = False
c.downloads.open_dispatcher = "xdg-open"

# ** Input
# don't timeout for during partially entered command
c.input.partial_timeout = 0

# ** Home/Start Page
c.url.default_page = "https://lwn.net/"
c.url.start_pages = ["https://lwn.net/"]

# ** Search Keywords
c.url.searchengines = {
    "DEFAULT": "https://duckduckgo.com/?q={}",
    "aw": "https://wiki.archlinux.org/index.php?search={}",
    "ap": "https://archlinux.org/packages/?q={}",
    "aur": "https://aur.archlinux.org/packages?O=0&K={}",
    "c": "https://crates.io/search?q={}",
    "d": "https://docs.rs/releases/search?query={}",
    "g": "https://startpage.com/do/asearch?q={}",
    "gh": "https://github.com/search?q={}",
    "h": "https://hackage.haskell.org/packages/search?terms={}",
    "hg": "https://www.haskell.org/hoogle/?hoogle={}",
    "mal": "https://myanimelist.net/search/all?q={}",
    "met": "https://www.metal-archives.com/search?searchString={}&type=band_name",
    "r": "https://www.reddit.com/r/{}/",
    "rt": "https://www.rottentomatoes.com/search/?search={}",
    "y": "https://www.youtube.com/results?search_query={}",
    "w": "https://en.wikipedia.org/w/index.php?title=Special:Search&search={}",
    "wayback": "https://web.archive.org/web/*/{}",
}

# ** Bookmarklets/Custom Commands
c.aliases["archive"] = "open --tab https://web.archive.org/save/{url}"
c.aliases["view-archive"] = "open --tab https://web.archive.org/web/*/{url}"
c.aliases["va"] = "open --tab https://web.archive.org/web/*/{url}"
c.aliases["view-google-cache"] = "open https://www.google.com/search?q=cache:{url}"
c.aliases["vgc"] = "open https://www.google.com/search?q=cache:{url}"

# Set a higher zoom level by default
c.zoom.default = "250%"

# Javascript
c.content.javascript.enabled = True

# Do not display PDFs in browser. pdfjs does not work.
c.content.pdfjs = False

c.content.blocking.adblock.lists = [
    "https://easylist.to/easylist/easylist.txt",
    "https://easylist.to/easylist/easyprivacy.txt",
    "https://easylist-downloads.adblockplus.org/indianlist.txt",
    "https://easylist-downloads.adblockplus.org/abp-filters-anti-cv.txt",
    "https://www.i-dont-care-about-cookies.eu/abp/",
    "https://easylist.to/easylist/fanboy-social.txt",
    "https://secure.fanboy.co.nz/fanboy-cookiemonster.txt",
    "https://secure.fanboy.co.nz/fanboy-annoyance.txt",
    "https://secure.fanboy.co.nz/fanboy-cookiemonster.txt",
]

# * Key Bindings
# ** Reload Configuration
nmap("ts", "config-source")

# Reload page
nunmap("r")
nunmap("R")
nmap("<Ctrl-r>", "reload")

# lose scroll left
nmap("h", "back")
nmap("H", "forward")

# lose scroll right
nmap("l", "tab-focus last")

# ** Colemak Swaps
# https://github.com/qutebrowser/qutebrowser/issues/2668#issuecomment-309098314
nmap("n", "scroll-page 0 0.2")
nmap("e", "scroll-page 0 -0.2")
nmap("N", "tab-prev")
# no default binding
nmap("E", "tab-next")

# add back search
nmap("k", "search-next")
nmap("K", "search-prev")

tmap("n", "move-to-next-line")
tmap("e", "move-to-prev-line")
tmap("i", "move-to-next-char")
# add back e functionality
tmap("j", "move-to-end-of-word")

tmap("N", "scroll down")
tmap("E", "scroll up")
tmap("I", "scroll right")

# ** Hinting
nmap("gi", "hint inputs")
# TODO ts for download hinting instead of :d
# TODO ti for image hinting in background (rebind :inspector)

# ** Miscellaneous
nmap("gn", "navigate previous")
nmap("ge", "navigate next")

nmap("tm", "messages --tab")
nmap("th", "help --tab")
nmap("tr", "stop")

# @: - run last ex command
nmap(
    "t;",
    "set-cmd-text : ;; completion-item-focus --history prev ;; " + "command-accept",
)

# ** Tabs and Windows
nmap("o", "set-cmd-text -s :open --tab")
nmap("O", "set-cmd-text -s :open")

# open homepage in new tab
nmap("tt", "open --tab")

# lose tab-only and download-clear
nmap("c", "set-cmd-text :open --related {url:pretty}")
nmap("C", "set-cmd-text :open --tab --related {url:pretty}")

# open new private window
nmap("tp", "open -p")

# tn and te for tab moving
nmap("tn", "tab-move -")
nmap("te", "tab-move +")
nmap("tw", "tab-close")

# ** TODO Tabgroups
# - title should be displayed somewhere
# - create new group (vn)
# - move tab to different group (vM; vm - without switching)
# - switch to different group (vv completion)
# - keys for specific tap groups (e.g. wr,  prog, main, mango)
# - rename tab group (vr)
# - delete tab group (vd)

# ** Yanking and Pasting
# don't need primary or extra yanks
nmap("p", "open --tab -- {clipboard}")
nmap("P", "open -- {clipboard}")
nmap("y", "yank")
nmap("Y", "yank selection")

# ** Editor
imap("<Ctrl-i>", "open-editor")
# open source in editor
nmap("gF", "view-source --edit")

# ** Insert/RL
# imap("<Ctrl-w>", "fake-key <Ctrl-backspace>")
imap("¸", "fake-key <Ctrl-backspace>")
cmap("¸", "fake-key --global <Ctrl-backspace>")

# nunmap('<Ctrl-w>')
# prevent c-w from closing tab
# del c.bindings.default["normal"]["<Ctrl-W>"]

# C-y for pasting
imap("<Ctrl-y>", "fake-key <Ctrl-v>")
cmap("<Ctrl-y>", "fake-key --global <Ctrl-v>")

# ** Passthrough
nmap(",", "enter-mode passthrough")
pmap("<Escape>", "leave-mode")

# ** Undo
# no :undo completion currently
# nmap('U', 'set-cmd-text --space :undo')

# ** Quickmarks and Marks
nunmap("'")

nmap("'c", ":open --tab https://chat.asymptotic.io/#/welcome")

nmap("'C", ":open --tab https://www.online.citibank.co.in/portal/pdf/card-Rate.pdf")
nmap(
    "'f",
    ":open --tab https://instantforex.icicibank.com/instantforex/forms/MicroCardRateView.aspx",
)
nmap(
    "'F",
    ":open --tab https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
)

nmap("'r", ":open --tab https://reddit.com/")
nmap("'e", ":open --tab https://www.reddit.com/r/emacs/")
nmap("'h", ":open --tab https://www.reddit.com/r/haskell/")
nmap("'n", ":open --tab https://www.reddit.com/r/neovim")
nmap("'v", ":open --tab https://www.reddit.com/r/vim/")
nmap("'q", ":open --tab https://www.reddit.com/r/qutebrowser/")

nmap("'a", ":open --tab https://wiki.archlinux.org/")
nmap("'A", ":open --tab https://9anime.vc/home")

nmap("'g", ":open --tab https://gitlab.freedesktop.org/gstreamer")
nmap("'G", ":open --tab https://www.github.com/")
nmap("'p", ":open --tab https://lazka.github.io/pgi-docs/#Gst-1.0")
nmap("'P", ":open --tab https://gitlab.freedesktop.org/pipewire")

nmap("'k", ":open --tab https://configure.zsa.io/planck-ez/layouts/XW39W/latest/0")
nmap("'L", ":open --tab https://www.last.fm/user/sanchayan_maity")
nmap("'m", ":open --tab https://man7.org/linux/man-pages/index.html")
nmap("'M", ":open --tab https://www.metal-archives.com/")
nmap("'s", ":open --tab https://myanimelist.net/anime/season")
nmap("'S", ":open --tab https://myanimelist.net/clubs.php?cid=27907")
nmap("'t", ":open --tab https://samples.mplayerhq.hu/A-codecs/")
nmap("'w", ":open --tab https://en.wikipedia.org/wiki/Main_Page")
nmap("'W", ":open --tab https://web.archive.org/web/*/{url}")
nmap("'y", ":open --tab https://youtube.com/")

# add back mark jumping
nmap('"', "enter-mode jump_mark")
nmap("tl", 'jump-mark "\'"')

# *** Playing Videos with MPV
nmap(",m", "spawn mpv {url}")
nmap(",M", "hint links spawn mpv {hint-url}")

# ** Downloads
# TODO download video and audio
# nmap -ex <leader>Y execute "silent !youtube-dl --restrict-filenames -o '~/move/%(title)s_%(width)sx%(height)s_%(upload_date)s.%(ext)s' " + buffer.URL + " &"
# nmap -ex <leader>A execute "silent !youtube-dl --restrict-filenames --extract-audio -o '~/move/%(title)s_%(width)sx%(height)s_%(upload_date)s.%(ext)s' " + buffer.URL + " &"
nmap("tg", 'spawn --detach dlg "{url}"')
nmap("td", "download-open")
nmap("tr", "download-delete")
nmap("tR", "set-cmd-text -s :download-delete")
nmap("tc", "download-clear")

# ** Zooming
nmap("zi", "zoom-in")
nmap("zo", "zoom-out")

# ** Inspector
nmap("ti", "inspector")

nunmap("gb")
nunmap("gB")
nmap("gb", "set-cmd-text -s :bookmark-load -t")
nmap("gB", "spawn --detach alacritty -e fish -c bo")
