# Path: misc/io.py
# def write(filename, string):
#   with open(filename, 'w') as f:
#     f.write(string)
# 
# def read(filename):
#   with open(filename, 'r') as f:
#     return f.read()


from misc.io import write, read
from os.path import expanduser
from time import time
import os
#SEARCH_OPTIONS = '--heuristic "hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=plusone),cost_type=plusone)" ' \
#                 '--search "lazy_wastar([hff,hlm],preferred=[hff,hlm],w=1,max_time=%s,bound=%s)"'
SEARCH_OPTIONS = '--heuristic "h=ff(transform=adapt_costs(cost_type=PLUSONE))" ' \
                 '--search "astar(h,max_time=%s,bound=%s)"'

SEARCH_COMMAND = FD_PATH + 'bin/downward %s < %s'%(SEARCH_OPTIONS, SAS_PATH) #+ ' --search-time-limit %s'%10 # TODO - limit

def write_sas(problem):
  s = write_version() + \
    write_action_costs() + \
    write_variables(problem) + \
    write_mutexes(problem) + \
    write_initial(problem) + \
    write_goal(problem) + \
    write_actions(problem) + \
    write_axioms(problem)
  write(SAS_PATH, s)

def fast_downward(debug=False, max_time=30, max_cost='infinity'):
  if os.path.exists(OUTPUT_PATH):
    os.remove(OUTPUT_PATH)
  command = SEARCH_COMMAND%(max_time, max_cost)
  t0 = time()
  p = os.popen(command)
  output = p.read()
  print(command, time() - t0)
  if debug:
    print(output)
  if not os.path.exists(OUTPUT_PATH):
    return None

# Path: misc/io.py
# def write(filename, string):
#   with open(filename, 'w') as f:
#     f.write(string)
# 
# def read(filename):
#   with open(filename, 'r') as f:
#     return f.read()


# Path: sas/downward.py
from misc.io import write, read
from os.path import expanduser
from time import time
import os

#SEARCH_OPTIONS = '--heuristic "hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=plusone),cost_type=plusone)" ' \
#                 '--search "lazy_wastar([hff,hlm],preferred=[hff,hlm],w=1,max_time=%s,bound=%s)"'
SEARCH_OPTIONS = '--heuristic "h=ff(transform=adapt_costs(cost_type=PLUSONE))" ' \
                 '--search "astar(h,max_time=%s,bound=%s)"'

SEARCH_COMMAND = FD_PATH + 'bin/downward %s < %s'%(SEARCH_OPTIONS, SAS_PATH) #+ ' --search-time-limit %s'%10 # TODO - limit

def write_sas(problem):
  s = write_version() + \
    write_action_costs() + \
    write_variables(problem) + \
    write_mutexes(problem) + \
    write_initial(problem) + \
    write_goal(problem) + \
    write_actions(problem) + \
    write_axioms(problem)
  write(SAS_PATH, s)

def fast_downward(debug=False, max_time=30, max_cost='infinity'):
  if os.path.exists(OUTPUT_PATH):
    os.remove(OUTPUT_PATH)
  command = SEARCH_COMMAND%(max_time, max_cost)
  t0 = time()
  p = os.popen(command)
  output = p.read()
  print(command, time() - t0)
  if debug:
    print(output)
  if not os.path.exists(OUTPUT_PATH):
    return None

  return read(OUTPUT_PATH)