import os
import sys
import math as m

import txt_read
import gcode_read
import move_parms
import plot_data
import job_parms
import gcode_write
import hotpath

###############

def starting_parameters(arguments):
  parms = job_parms.typical()

  test_parms = starting_test_parms(arguments, parms)

  mp_trace_raster = move_parms.make(parms['solid_raster_width'], parms['acceleration'], parms['job_filling_speed'], 0)
  mp_jump = move_parms.make(0, parms['acceleration'], parms['job_jump_speed'], parms['extrusion_on_off_time'])

  return parms, test_parms, mp_trace_raster, mp_jump

def starting_test_parms(arguments, parms):
  test_parms = {
    'input_file': '',
    'output_file': '',
    'gcode_file': '',
    'image_file': '',
    'limit_time': m.inf,
    'max_lines': m.inf,
    'best': True,
    'prune': 'True',
    'delta': m.inf,
    'angle': 0,
    'start_point': (0,0),
    'Z': 0,
    'n_slice': 1,
    'debug': True
  }

  if arguments[2] != 'inf':
    test_parms['delta'] = float(arguments[2])
  
  if arguments[3] != 'inf':
    test_parms['limit_time'] = int(arguments[3])
   
  if arguments[4] == 'False':
    test_parms['best'] = False

  test_parms['prune'] = arguments[5]
  
  if arguments[6] == 'False':
    test_parms['debug'] = False  

  create_folder(test_parms, parms, arguments[1])
  
  return test_parms

def create_folder(test_parms, parms, input_name):
  test_parms['input_file'] = './tests/in/' + input_name

  if '_90' in test_parms['input_file']:
    test_parms['angle'] = 1.5708

  output_folder = input_name.replace('.txt', '')
  output_folder = output_folder.replace('.gcode', '')

  if '.txt' in input_name:
    delta = str(test_parms['delta']).replace('.0', '')
    limit_time = str(test_parms['limit_time'])
    best = str(test_parms['best'])
    prune = str(test_parms['prune'])
    output_folder += '_delta' + delta + '_limit' + limit_time + '_best' + best + '_prune' + prune

  if not os.path.exists('./tests/out/' + output_folder):
    os.makedirs('./tests/out/' + output_folder)
  
  if not os.path.exists('./tests/out/' + output_folder + '/debug') and test_parms['debug']:
    os.makedirs('./tests/out/' + output_folder + '/debug')
  
  test_parms['output_file'] = './tests/out/' + output_folder + '/' + output_folder + '.txt'
  test_parms['output_file'] = open(test_parms['output_file'], 'w')
  test_parms['gcode_file'] = './tests/out/' + output_folder + '/' + output_folder + '.gcode'
  test_parms['image_file'] = './tests/out/' + output_folder + '/' + output_folder 

  if '.txt' in input_name:
    ex_temp = parms['nozzle_temperature']
    gcode_write.file_preamble(open(test_parms['gcode_file'], 'w'), ex_temp)

  if '.gcode' in input_name:
    find_n_slice(test_parms, input_name)
  
  return

def find_n_slice(test_parms, input_file):
  n_slice_list = [ 
    ('adfoot', 5),
    ('runleg', 15),
    ('wingn', 3)
  ]

  for n in n_slice_list:   
    if n[0] in input_file:
      test_parms['n_slice'] = n[1]
  
  return

def print_error(f):
  f.write('Not Found')

###############

arguments = sys.argv
#arguments = ['', 'hlatch_1_0.txt', '30', '60', 'False', 'FalseB', 'False']

parms, test_parms, mp_trace_raster, mp_jump = starting_parameters(arguments)

if '.txt' in test_parms['input_file']:
  Z, R, S, p = txt_read.read_txt(test_parms['input_file'], mp_trace_raster, test_parms['angle'])
  number_lines = len(R)
  BS, CS = txt_read.create_blocks(R, S, p, mp_jump, test_parms['angle'], test_parms['delta'])

  if BS == None:
    print_error(test_parms['output_file'])
  
  else:
    c_box = plot_data.plot_input(test_parms['image_file'], 4, BS, CS, test_parms['start_point'], parms)
    
    if test_parms['prune'] == 'True':
      Q, time = hotpath.best_path(test_parms['output_file'], BS, CS, test_parms['start_point'], mp_jump, test_parms['delta'], test_parms['limit_time'], test_parms['best'], test_parms['prune'], parms, number_lines, test_parms['debug'], c_box)
    else:
      Q, time = hotpath.best_path_2(test_parms['output_file'], BS, CS, test_parms['start_point'], mp_jump, test_parms['delta'], test_parms['limit_time'], test_parms['best'], test_parms['prune'], parms, number_lines, test_parms['debug'], c_box)  
    
elif '.gcode' in test_parms['input_file']:
    if '_rp3' in test_parms['input_file']:
      C, R, start_point = gcode_read.read_gcode_rp3(test_parms['input_file'], test_parms['n_slice'])

    elif '_slic3r' in test_parms['input_file']:
      C, R, start_point = gcode_read.read_gcode_slic3r(test_parms['input_file'], test_parms['n_slice'])

    test_parms['start_point'] = start_point
    R, max_group = gcode_read.create_lines(R, test_parms['angle'], mp_trace_raster)
    S = gcode_read.find_contacts(R, parms['solid_raster_width'], test_parms['angle'])

    BS, CS = gcode_read.create_blocks(R, S, max_group, test_parms['angle'])

    c_box = plot_data.plot_input(test_parms['image_file'], 1, BS, CS, test_parms['start_point'], parms)
    
    Q, start_point = hotpath.original_path(test_parms['output_file'], BS, CS, mp_jump)


if Q != None:
  plot_data.plot_solution(test_parms['image_file'], Q, c_box, test_parms, parms)

  if '.gcode' not in test_parms['input_file']:
    f = open(test_parms['gcode_file'], 'a')
    gcode_write.file_postamble(f)
    
    

  if Qbest != None and contact.max_tcool(Qbest, CS) <= Delta:
    Qbest = remove_first_jump(Qbest)
    describe_solution(wr, Qbest, CS, Delta, ncalls, ntime)
  else:
    describe_fail(wr, Delta, ncalls, ntime)
    
