#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Kevin Lyda <kevin@phrye.com>
#
# Distributed under terms of the GPL license.
from __future__ import print_function

"""
COBOL utilities.
"""

# See :help python-vim for how this module works.
import vim
import math

try:
  xrange
except NameError:
  xrange = range

def cobol_Renumber():
  # Is this COBOL?
  if vim.current.buffer.options['filetype'] != b'cobol':
    print('Not a COBOL file. This is a %s file.' %
        vim.current.buffer.options['filetype'].decode('UTF-8'))
    return

  # Get user configs.
  try:
    min_delta = int(vim.eval('g:cobol_minimum_delta'))
    if min_delta < 1:
      min_delta = 1
  except:
    min_delta = 1
  try:
    max_delta = int(vim.eval('g:cobol_maximum_delta'))
    if max_delta < min_delta:
      max_delta = max(100, min_delta)
  except:
    max_delta = max(100, min_delta)

  gap = {}
  last_line_no = 0
  lines = vim.current.buffer

  # Look for gaps.
  for i in xrange(len(lines)):
    if len(lines[i]) == 0 or lines[i][:6].isspace():
      if not gap:
        gap['i'] = i
        gap['last_line_no'] = last_line_no
    else:
      try:
        last_line_no = int(lines[i][:6])
      except ValueError:
        print('Error: line %d has non-numbers in columns 1-6' % (i + 1))
        return
      if gap:
        delta = math.floor((last_line_no - gap['last_line_no']) /
          (i - gap['i'] + 1))
        if delta > min_delta:
          delta = min(delta, max_delta)
          new_line_no = gap['last_line_no'] + delta
          for j in xrange(gap['i'], i):
            lines[j] = ('%06d' % new_line_no) + lines[j][6:]
            new_line_no += delta
          gap = {}

  # Deal with gap at end of file.
  if gap:
    new_line_no = gap['last_line_no'] + max_delta
    for j in xrange(gap['i'], len(lines)):
      lines[j] = ('%06d' % new_line_no) + lines[j][6:]
      new_line_no += max_delta

def cobol_Unnumber():
  if vim.current.buffer.options['filetype'] != b'cobol':
    print('Not a COBOL file. This is a %s file.' %
        vim.current.buffer.options['filetype'].decode('UTF-8'))

  lines = vim.current.buffer
  for i in xrange(len(lines)):
    if lines[i][:6].isdigit():
      lines[i] = '      ' + lines[i][6:]