#!/usr/bin/python

import re
import os
import sys
import json
import argparse
import pyjsonrpc

from absinthe.tools.config import Config
from absinthe.tools.utils import SimpleResponse

absinthe_data_dir = os.path.join(os.path.expanduser('~'), '.absinthe')

config_data = {}
with open(os.path.join(absinthe_data_dir, 'config.json')) as f:
    config_data = json.load(f)

try:
    config = Config(None)
    config.load(config_data['server'])
except Exception as e:
    print "Cannot load config: " % e
    sys.exit(1)

config_raw = config.raw()

parser = argparse.ArgumentParser()
parser.add_argument('files', type = str, nargs='+')
parser.add_argument('-p', '--path_base', type = str, choices = config_raw['paths'].keys(), default = config_raw['default-path'])
parser.add_argument('-v', '--verbose', action = 'store_true')
parser.add_argument('-f', '--nofs', help = 'No set focus to editor after file open', action = 'store_true')
parser.add_argument('-t', '--touch', help = 'Create the specified file(s) if not exists', action = 'store_true')
args = parser.parse_args()

client = pyjsonrpc.HttpClient(url = "http://%(host)s:%(port)d/jsonrpc" % config_raw['command_server'])

for file in args.files:
    filename = file
    line = 0
    line_reg = re.search('(.+):([0-9]{1,})$', filename)

    if line_reg:
        filename = line_reg.group(1)
        line = line_reg.group(2)

    if os.path.isfile(filename) is False:
        if args.touch:
            if os.path.exists(filename):
                print "Path: '%s' is exists, but not a file, so will not be created. Skipping." % filename
                continue
            with open(filename, 'w') as f:
                f.write("\n")
        else:
            print "File: '%s' is not exists!" % filename
            continue

    try:
        response = client.open_file(args.path_base, os.path.abspath(filename), int(line))
        resp = SimpleResponse(**response)
        if resp.code != True or args.verbose:
            for msg in resp.message:
                print msg
    except Exception as e:
        raise e

if not args.nofs:
    client.set_focus(args.path_base)
