#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import optparse

from os.path import join as j

from os import sep

from pairtree import id_encode, id_decode

from io import StringIO

def _option_parser():
    parser = optparse.OptionParser()
    parser.add_option("-v", "--verbose", dest="verbose",
                  action="store_true",
                  help="Log information to stdin as it goes",
                  default=False)
    return parser

if __name__ == '__main__':
    o = _option_parser()
    values, args = o.parse_args()
    if len(args)>0:
        cmd = args[0]
    else:
        cmd = ""
    if values.verbose:
        logger.setLevel(logging.DEBUG)

    if cmd == 'topath':
        if len(args) == 1:
            sys.exit("Need to pass an id or id/subpath to this command")
        frags = args[1].split(sep, 1)
        path = None
        if len(frags)>1:
            ident, path = frags
        else:
            ident = frags[0]
        encodedid = id_encode(ident)
        filepath = []
        while encodedid:
            filepath.append(encodedid[:2])
            encodedid = encodedid[2:]
        if path:
            filepath.append(path)
        print(j(*filepath))
    elif cmd == 'toid':
        if len(args) == 1:
            sys.exit("Need to pass a filepath to this command")
        tokens = args[1].split(sep)
        id_parts = []
        root = []
        while not len(tokens[0]) == 2:
            root.append(tokens.pop(0))
            if len(tokens) == 0:
                sys.exit("Couldn't recoginise a pairtree encoded path in the parameter")
        index = 0
        while index < len(tokens):
            part = tokens[index]
            if len(part) == 1:
                # split end ending
                id_parts.append(part)
                index = index + 1
                break
            elif len(part) == 2:
                id_parts.append(part)
                index = index + 1
            else:
                break
        ident = id_decode("".join(id_parts))
#        if root:
#            root = j(*root)
#            ident = j(root, ident)
        remnants = tokens[index:]
        if remnants:
            ident = j(ident, *remnants)
        print(ident)
    elif cmd == 'help' or cmd == "":
        print("ppath topath [id] - converts an id or id/subpath into a pairtree directory path")
        print("ppath toid [path] - converts a filepath into an id or id/subpath")
    elif len(args) == 1:
        # Assume topath - eg ppath foo:1 -> reads as -> ppath topath foo:1
        frags = args[0].split(sep, 1)
        path = None
        if len(frags)>1:
            ident, path = frags
        else:
            ident = frags[0]
        encodedid = id_encode(ident)
        filepath = []
        while encodedid:
            filepath.append(encodedid[:2])
            encodedid = encodedid[2:]
        if path:
            filepath.append(path)
        print(j(*filepath))
    else:
        print("unknown command: %s" % cmd)
        print("ppath topath [id] - converts an id or id/subpath into a pairtree directory path")
        print("ppath toid [path] - converts a filepath into an id or id/subpath")

