#!/usr/bin/env python3

import sys
sys.path.insert(1, '../lib')
import argparse
from datetime import datetime
from geopy.distance import distance
import lmdk_bgt
import lmdk_lib
import numpy as np
from matplotlib import pyplot as plt
import time


def main(args):
  # The data files
  data_files = {
    'T-drive': '/home/manos/Cloud/Data/T-drive/Results.zip',
  }
  # Data related info
  data_info = {
    'T-drive': {
      'uid': 2,
      'lmdks': {
          0: {'dist': 0, 'per': 1000},   #   0.0%
         20: {'dist': 2095, 'per': 30},  #  19.6%
         40: {'dist': 2790, 'per': 30},  #  40.2%
         60: {'dist': 3590, 'per': 30},  #  59.9%
         80: {'dist': 4825, 'per': 30},  #  79.4%
        100: {'dist': 10350, 'per': 30}  # 100.0%
      }
    }
  }
  # The data sets
  data_sets = {}
  # Load data sets
  for df in data_files:
    args.res = data_files[df]
    data_sets[df] = lmdk_lib.load_data(args, 'usrs_data')
  # Geo-I configuration
  # epsilon = level/radius
  # Radius is in meters
  bgt_conf = [
    {'epsilon': 1},
  ]

  # Number of methods
  n = 3
  # Width of bars
  bar_width = 1/(n + 1)
  # The x axis
  x_i = np.arange(len(list(data_info.values())[0]['lmdks']))
  x_margin = bar_width*(n/2 + 1)

  for d in data_sets:
    print('\n##############################', d, '\n')
    args.res = data_files[d]
    data = data_sets[d]
    # Truncate trajectory according to arguments
    seq = data[data[:,0]==data_info[d]['uid'], :][:args.time]

    # Initialize plot
    lmdk_lib.plot_init()
    # The x axis
    plt.xticks(x_i, np.array([key for key in data_info[d]['lmdks']]).astype(int))
    plt.xlabel('Landmarks (%)')  # Set x axis label.
    plt.xlim(x_i.min() - x_margin, x_i.max() + x_margin)
    # The y axis
    plt.ylabel('Mean absolute error (m)')  # Set y axis label.
    plt.yscale('log')
    plt.ylim(1, 1000000)
    # Bar offset
    x_offset = -(bar_width/2)*(n - 1)

    mae_u = np.zeros(len(data_info[d]['lmdks']))
    mae_s = np.zeros(len(data_info[d]['lmdks']))
    mae_a = np.zeros(len(data_info[d]['lmdks']))
    mae_d = np.zeros(len(data_info[d]['lmdks']))
    mae_evt = 0
    mae_usr = 0
    for i, lmdk in enumerate(data_info[d]['lmdks']):
      # Find landmarks
      args.dist = data_info[d]['lmdks'][lmdk]['dist']
      args.per = data_info[d]['lmdks'][lmdk]['per']
      lmdks = lmdk_lib.find_lmdks(seq, args)
      for bgt in bgt_conf:
        s_d = 0
        for _ in range(args.iter):
          # Skip
          rls_data_s, _ = lmdk_bgt.skip(seq, lmdks, bgt['epsilon'])
          mae_s[i] += lmdk_bgt.mae(seq, rls_data_s)/args.iter

          # Uniform
          rls_data_u, _ = lmdk_bgt.uniform_r(seq, lmdks, bgt['epsilon'])
          mae_u[i] += lmdk_bgt.mae(seq, rls_data_u)/args.iter

          # Adaptive
          rls_data_a, _, _ = lmdk_bgt.adaptive(seq, lmdks, bgt['epsilon'], .5, .5)
          mae_a[i] += lmdk_bgt.mae(seq, rls_data_a)/args.iter

          # # Dynamic
          # rls_data_a, _, s_d_c = lmdk_bgt.dynamic(seq, lmdks, bgt['epsilon'], .5, .5)
          # mae_d[i] += lmdk_bgt.mae(seq, rls_data_a)/args.iter
          # s_d += s_d_c/args.iter

          # Calculate once
          if lmdk == min(data_info[d]['lmdks']):
            # Event
            rls_data_evt, _ = lmdk_bgt.uniform_r(seq, lmdks, bgt['epsilon'])
            mae_evt += lmdk_bgt.mae(seq, rls_data_evt)/args.iter
          elif lmdk == max(data_info[d]['lmdks']):
            # User
            rls_data_usr, _ = lmdk_bgt.uniform_r(seq, lmdks, bgt['epsilon'])
            mae_usr += lmdk_bgt.mae(seq, rls_data_usr)/args.iter

    # Plot lines
    plt.axhline(
      y = mae_evt,
      color = '#212121',
      linewidth=lmdk_lib.line_width
    )
    plt.text(x_i[-1] + x_i[-1]*.14, mae_evt - mae_evt*.14, 'event')
    plt.axhline(
      y = mae_usr,
      color = '#616161',
      linewidth=lmdk_lib.line_width
    )
    plt.text(x_i[-1] + x_i[-1]*.14, mae_usr - mae_usr*.14, 'user')

    # Plot bars
    plt.bar(
      x_i + x_offset,
      mae_s,
      bar_width,
      label='Skip',
      linewidth=lmdk_lib.line_width
    )
    x_offset += bar_width
    plt.bar(
      x_i + x_offset,
      mae_u,
      bar_width,
      label='Uniform',
      linewidth=lmdk_lib.line_width
    )
    x_offset += bar_width
    plt.bar(
      x_i + x_offset,
      mae_a,
      bar_width,
      label='Adaptive',
      linewidth=lmdk_lib.line_width
    )
    # x_offset += bar_width
    # plt.bar(
    #   x_i + x_offset,
    #   mae_d,
    #   bar_width,
    #   label='Dynamic',
    #   linewidth=lmdk_lib.line_width
    # )

    path = str('../../rslt/bgt_cmp/' + d)
    # Plot legend
    lmdk_lib.plot_legend()
    # Show plot
    # plt.show()
    # Save plot
    lmdk_lib.save_plot(path + '.pdf')
    print('[OK]', flush=True)


def parse_args():
  '''
    Parse arguments.

    Optional:
      dist - The coordinates distance threshold in meters.
      per  - The timestaps period threshold in mimutes.
      time - The total timestamps.
      iter - The total iterations.
  '''
  # Create argument parser.
  parser = argparse.ArgumentParser()

  # Mandatory arguments.

  # Optional arguments.
  parser.add_argument('-l', '--dist', help='The coordinates distance threshold in meters.', type=int, default=200)
  parser.add_argument('-p', '--per', help='The timestaps period threshold in mimutes.', type=int, default=30)
  parser.add_argument('-r', '--res', help='The results archive file.', type=str, default='/home/manos/Cloud/Data/T-drive/Results.zip')
  parser.add_argument('-t', '--time', help='The total timestamps.', type=int, default=1000)
  parser.add_argument('-i', '--iter', help='The total iterations.', type=int, default=1)

  # Parse arguments.
  args = parser.parse_args()

  return args


if __name__ == '__main__':
  try:
    start_time = time.time()
    main(parse_args())
    end_time = time.time()
    print('##############################')
    print('Time elapsed: %s' % (time.strftime('%H:%M:%S', time.gmtime(end_time - start_time))))
    print('##############################')
  except KeyboardInterrupt:
    print('Interrupted by user.')
    exit()
