import hotpath

import contour
import path

import txt_read
import gcode_read
import gcode_write
import plot_data
import job_parms
import move_parms

import os
import sys
import math as m

def create_folder(test_parms):
  fname = test_parms['input_file'].split('.')
  fname = fname[0]
  output_folder = './tests/out/' + fname + ' [DELTA ' + str(test_parms['delta'])

  if test_parms['split_lines']:
    output_folder += " - SPLIT"

  if test_parms['limit_lines']:
    output_folder += " - LIMIT#" + str(test_parms['max_lines'])

  output_folder += ']'

  if not os.path.exists(output_folder):
    os.makedirs(output_folder)
  
  output_folder += "/"

  if test_parms['debug']:
    if not os.path.exists(output_folder + '/debug'):
      os.makedirs(output_folder + '/debug')
    else:
      for filencalls in os.listdir(output_folder + '/debug'):
        if "ncall" in filencalls:
          os.remove(output_folder + '/debug/' + filencalls)
  elif os.path.exists(output_folder + '/debug'):
      for filencalls in os.listdir(output_folder + '/debug'):
        if "ncall" in filencalls:
          os.remove(output_folder + '/debug/' + filencalls)

  output_file = test_parms['input_file']

  if '.gcode' in output_file:
    output_file = output_file.replace('.gcode', '')
  else:
    test_parms['input_folder'] =  './tests/in/' + output_file + '/'
    
  output_file = output_folder + output_file
  
  test_parms['output_file'] = output_file
  test_parms['output_folder'] = output_folder

  test_parms['gcode'] = test_parms['output_folder'] + test_parms['input_file']
  if '.gcode' not in test_parms['gcode']:
    test_parms['gcode'] += '.gcode'
  
  return
  # ----------------------------------------------------------------------

###############

def create_input(test_parms, parms):
  mp_trace_contour = move_parms.make(parms['contour_trace_width'], parms['acceleration'], parms['job_contour_speed'], 0)
  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'])

  CTRS, BS, CS, c_box = None, None, None, None

  if '.gcode' in test_parms['input_file']:
    test_parms['input_file'] = test_parms['input_file'].replace('.gcode', '')
    CTRS, BS, CS = create_input_gcode(test_parms, mp_trace_contour, mp_trace_raster, mp_jump)
    test_parms['input_file'] = test_parms['input_file'] + '_' + str(test_parms['islice'])
  
  else:
    test_parms['input_file'] = test_parms['input_file'].replace('.txt', '')
    CTRS, BS, CS = create_input_txt(test_parms, parms, mp_trace_contour, mp_trace_raster, mp_jump)
  
  if BS != [] and BS != None:
    c_box = plot_data.plot_input(test_parms['output_folder'] + test_parms['input_file'], CTRS, BS, CS, test_parms['o'], parms)  
    c_box.append(test_parms['output_folder'] + 'debug/' + test_parms['input_file'])

    if test_parms['islice'] == 1:
      ex_temp = parms['nozzle_temperature']
      gcode_write.file_preamble(open(test_parms['gcode'], 'w'), ex_temp)

  return CTRS, BS, CS, mp_jump, c_box

def create_input_gcode(test_parms, mp_trace_contour, mp_trace_raster, mp_jump):
  Z, contour_points, raster_points = gcode_read.read_gcode(test_parms['input_file'], test_parms['islice'])

  test_parms['Z'] = Z

  CTRS = contour.create_contour(contour_points, mp_trace_contour, mp_jump)

  R, S, NB = gcode_read.create_raster_lines(test_parms['islice'], raster_points, mp_trace_raster, test_parms['angle'])
  
  if test_parms['split_lines']:
    NB = gcode_read.split_block(R, NB, S)

  if test_parms['limit_lines']:
    NB = gcode_read.limit_block(R, NB, S, test_parms['max_lines'])

  BS, CS = gcode_read.create_blocks(R, S, CTRS, NB, mp_trace_raster, mp_jump, test_parms['angle'])
  
  return CTRS, BS, CS
  # ----------------------------------------------------------------------

def create_input_txt(test_parms, parms, mp_trace_contour, mp_trace_raster, mp_jump):
  Z, contour_points, R, S, NB = txt_read.read_txt(test_parms['input_folder'] + test_parms['input_file'], mp_trace_raster, test_parms['angle'])
  
  test_parms['Z'] = Z

  CTRS = contour.create_contour(contour_points, mp_trace_contour, mp_jump)

  if test_parms['split_lines']:
    NB = txt_read.split_block(R, NB)
  
  if test_parms['limit_lines']:
    NB = txt_read.limit_block(R, NB, test_parms['max_lines'], S)
  
  if test_parms['split_lines'] or test_parms['limit_lines']:
    txt_read.delete_rasterLink(R)
  
  BS, CS = txt_read.create_blocks(R, S, CTRS, NB, mp_trace_raster, mp_jump, test_parms['angle'])

  return CTRS, BS, CS

###############
def test_txt(test_parms, parms):
  filename = test_parms['input_file'] 

  if test_parms['max_slice'] != None:
    test_parms['max_slice'] += 1
  else:
    test_parms['max_slice'] = len(os.listdir(test_parms['input_folder'])) + 1

  for test_parms['islice'] in range(test_parms['islice'], test_parms['max_slice'], 1):
    test_parms['input_file'] = filename + '_' + str(test_parms['islice']) + '.txt'

    CTRS, BS, CS, mp_jump, c_box = create_input(test_parms, parms)

    sys.stdout = open(test_parms['output_file'] + '_' + str(test_parms['islice']) + ".txt", 'w')

    Q = hotpath.find_solution(CTRS, BS, CS, mp_jump, parms, test_parms, c_box, sys.stdout)

    if Q != None:
      plot_data.plot_solution(test_parms['output_folder'] + test_parms['input_file'] + "_sol", Q, c_box, test_parms, parms)
      test_parms['o'] = path.pfin(Q)

  f = open(test_parms['gcode'], 'a')
  gcode_write.file_postamble(f)

  return

def test_gcode(test_parms, parms):
  filename = test_parms['input_file']

  while(True):
    test_parms['input_file'] = filename
    CTRS, BS, CS, mp_jump, c_box = create_input(test_parms, parms)
    
    if BS == [] or BS == None:
      break
    
    sys.stdout = open(test_parms['output_file'] + '_' + str(test_parms['islice']) + ".txt", 'w')
    
    Q = hotpath.find_solution(CTRS, BS, CS, mp_jump, parms, test_parms, c_box, sys.stdout)

    if Q != None:
      plot_data.plot_solution(test_parms['output_folder'] + test_parms['input_file'] + "_sol", Q, c_box, test_parms, parms)
      test_parms['o'] = path.pfin(Q)
    
    test_parms['islice'] += 1

    if test_parms['max_slice'] != None and test_parms['islice'] > test_parms['max_slice']:
      break

  f = open(test_parms['gcode'], 'a')
  gcode_write.file_postamble(f)

  return

###############
test_parms = {
    'input_file': 'peca_ilhas_v2.gcode',
    #'input_file': 'peca_ilhas_v2',
    'output_file': '',
    'output_folder': '',
    'islice': 1,
    'max_slice': 5,
    'angle': 1.5708,
    'Z': 0,
    'o': (0, 0),
    'delta': 65,
    'max_calls': 1000,
    'split_lines': True,
    'limit_lines': True,
    'max_lines': 25,
    'use_raster_links': True,
    'debug': False
  }

parms = job_parms.typical()

create_folder(test_parms)

if 'gcode' in test_parms['input_file']:
  test_gcode(test_parms, parms)
else:
  test_txt(test_parms, parms)