#! /usr/bin/python3
# Last edited on 2021-05-16 06:42:08 by jstolfi

import hotpath_elis

import move
import move_parms
import path
import block
import block_hp
import contour
import contour_hp
import contact
import contact_hp
import job_parms
import hacks

import path_example
import input_data_elis
import txt_read
import gcode_read_elis
import gcode_write_elis
import plot_data

import rn
import pyx
import os
import sys
import time
from math import sqrt, sin, cos, floor, ceil, inf, nan, pi

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

  CRS, BCS, CTS, c_box = None, None, None, None

  if '.gcode' in test_parms['input_file']:
    test_parms['input_file'] = test_parms['input_file'].replace('.gcode', '')
    CRS, BCS, CTS = create_input_gcode(test_parms, mp_cont, mp_fill, 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', '')
    CRS, BCS, CTS = create_input_txt(test_parms, parms, mp_cont, mp_fill, mp_jump)
  
  if BCS != [] and BCS != None:
    c_box = plot_data.plot_input(test_parms['output_folder'] + test_parms['input_file'], CRS, BCS, CTS, 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_elis.file_preamble(open(test_parms['gcode'], 'w'), ex_temp)

  return CRS, BCS, CTS, mp_cont, mp_jump, c_box

def create_input_gcode(test_parms, mp_cont, mp_fill, mp_jump):
  Z, PTSS, raster_points = gcode_read_elis.read_gcode(test_parms['input_file'], test_parms['islice'])

  test_parms['Z'] = Z

  CRS = contour.from_point_lists(PTSS, mp_cont, mp_jump)

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

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

  BCS, CTS = gcode_read_elis.create_blocks(R, S, CRS, NB, mp_fill, mp_jump, test_parms['angle'])
  
  return CRS, BCS, CTS
  # ----------------------------------------------------------------------

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

  CRS = contour.from_point_lists(PTSS)

  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)
  
  BCS, CTS = txt_read.create_blocks(R, S, CRS, NB, mp_fill, mp_jump, test_parms['angle'])

  return CRS, BCS, CTS

###############
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'

    CRS, BCS, CTS, mp_cont, mp_jump, c_box = create_input(test_parms, parms)

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

    Q = hotpath_elis.find_solution(CRS, BCS, CTS, mp_cont, 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_elis.file_postamble(f)

  return

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

  while(True):
    test_parms['input_file'] = filename
    CRS, BCS, CTS, mp_cont, mp_jump, c_box = create_input(test_parms, parms)
    
    if BCS == [] or BCS == None:
      break
    
    sys.stdout = open(test_parms['output_file'] + '_' + str(test_parms['islice']) + ".txt", 'w')
    
    Q = hotpath_elis.find_solution(CRS, BCS, CTS, mp_cont, 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_elis.file_postamble(f)

  return

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
  # ----------------------------------------------------------------------

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_elis()

create_folder(test_parms)

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