#!/usr/bin/env python3

#purpose:

#o take a note of every dir that I have been to.
#o `cd ori xx' should list the dirs that match these tokens,
#o better yet, it should allow me to choose which one and the change into it.
#o The dir history should be in the order that's last visited.

#cd ori ext

import os
from pkg.ordered_set import *
import sys


where_file = os.path.expanduser("~/.cache/init/.where")


def where_pushd():
    pwd = os.environ['PWD']
    if '/.cache/system-config/for-code-reading' in pwd or '/smb' in pwd or '//' in pwd or '/mnt/' in pwd or '/run/' in pwd:
        return


    if not os.path.exists(where_file):
        fil_ = open(where_file, 'w', encoding="utf-8")
        fil_.close()

    dir_history = open(where_file, encoding="utf-8").read().split('\n');
    dir_history[:0] = [pwd]
    dir_history = OrderedSet(dir_history);

    for x in OrderedSet(dir_history):
        if not (os.path.exists(x) and os.path.isdir(x)):
            dir_history.discard(x)

    dir_history.add('')
    where_file_tmp = where_file + ('.%d' % os.getpid())
    fil_ = open(where_file_tmp, 'w', encoding="utf-8")
    fil_.write('\n'.join(dir_history))
    fil_.close();
    os.rename(where_file_tmp, where_file)

def where_ask(argv):
    dir_history = open(where_file, encoding="utf-8").read().split('\n');
    for dir in dir_history:
        if all([x.lower() in dir.lower() for x in argv]):
            if any([x.lower() in dir.split('/')[-1].lower() for x in argv]):
                if (os.path.exists(dir)):
                    print(dir)

if sys.argv[1:]:
    where_ask(sys.argv[1:])
else:
    where_pushd()

