from gosubl import about
from gosubl import gs
from gosubl import gsshell
from gosubl import mg9
from gosubl import sh
import datetime
import json
import os
import re
import shlex
import string
import sublime
import sublime_plugin
import uuid
import webbrowser

DOMAIN = "9o"
AC_OPTS = sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS
SPLIT_FN_POS_PAT = re.compile(r"(.+?)(?:[:](\d+))?(?:[:](\d+))?$")
URL_SCHEME_PAT = re.compile(r"^[\w.+-]+://")
URL_PATH_PAT = re.compile(
    r"^(?:[\w.+-]+://|(?:www|(?:\w+\.)*(?:golang|pkgdoc|gosublime)\.org))"
)
HIST_EXPAND_PAT = re.compile(r"^(\^+)\s*(\d+)$")

HOURGLASS = u"\u231B"

DEFAULT_COMMANDS = [
    "help",
    "run",
    "build",
    "replay",
    "clear",
    "tskill",
    "tskill replay",
    "tskill go",
    "go",
    "go build",
    "go clean",
    "go doc",
    "go env",
    "go fix",
    "go fmt",
    "go get",
    "go install",
    "go list",
    "go run",
    "go test",
    "go tool",
    "go version",
    "go vet",
    "go help",
    "settings",
    "env",
    "share",
    "hist",
    "hist erase",
    "cd",
]
DEFAULT_CL = [(s, s + " ") for s in DEFAULT_COMMANDS]

stash = {}
tid_alias = {}


def active_wd(win=None):
    _, v = gs.win_view(win=win)
    return gs.basedir_or_cwd(v.file_name() if v else "")


def _hkey(wd):
    name = gs.setting("9o_instance")
    if name:
        wd = name
    return "9o.hist.%s" % wd


def _wdid(wd):
    name = gs.setting("9o_instance")
    if name:
        return name
    return "9o://%s" % wd


class EV(sublime_plugin.EventListener):
    def on_query_completions(self, view, prefix, locations):
        pos = gs.sel(view).begin()
        if view.score_selector(pos, "text.9o") == 0:
            return []

        cl = set()

        hkey = _hkey(view.settings().get("9o.wd", ""))
        cl.update((k, k + " ") for k in gs.dval(gs.aso().get(hkey), []))
        cl.update((k, k + " ") for k in aliases())
        cl.update((k, k + " ") for k in builtins())
        cl.update(DEFAULT_CL)

        return ([cl_esc(e) for e in sorted(cl)], AC_OPTS)


def cl_esc(e):
    return (e[0], e[1].replace("$", "\\$"))


class Gs9oBuildCommand(sublime_plugin.WindowCommand):
    def is_enabled(self):
        view = gs.active_valid_go_view(self.window)
        return view is not None

    def run(self):
        view = self.window.active_view()
        args = (
            {"run": gs.setting("build_command", ["^1"])} if gs.is_pkg_view(view) else {}
        )