#!/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 lmdk_sel
import exp_mech
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},
  ]
  eps_pct = [.01, .1, .25, .5]

  markers = [
    '^',
    'v',
    'D',
    's'
  ]

  # The x axis
  x_i = np.arange(len(list(data_info.values())[0]['lmdks']))

  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_i.max())
    # The y axis
    plt.ylabel('Mean absolute error (m)')  # Set y axis label.

    mae_evt = 0
    mae_usr = 0

    for i_e, e in enumerate(eps_pct):
      mae = np.zeros(len(data_info[d]['lmdks']))
      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)[:args.time]
        for bgt in bgt_conf:
          for _ in range(args.iter):

            lmdks_sel = lmdk_sel.find_lmdks_eps(seq, lmdks, bgt['epsilon']*e)

            # Uniform
            rls_data_u, _ = lmdk_bgt.uniform_r(seq, lmdks_sel, bgt['epsilon']*(1 - e))
            mae[i] += lmdk_bgt.mae(seq, rls_data_u)/args.iter

            # Calculate once
            if e == eps_pct[0] and 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 e == eps_pct[-1] and 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 line
      plt.plot(
        x_i,
        mae,
        label='{0:.2f}'.format(e) + 'ε',
        marker=markers[i_e],
        markersize=lmdk_lib.marker_size,
        markeredgewidth=0,
        linewidth=lmdk_lib.line_width
      )

    plt.axhline(
      y = mae_evt,
      color = '#212121',
      linewidth=lmdk_lib.line_width
    )
    plt.text(x_i[-1] + x_i[-1]*.01, mae_evt - mae_evt*.05, 'event')

    plt.axhline(
      y = mae_usr,
      color = '#616161',
      linewidth=lmdk_lib.line_width
    )
    plt.text(x_i[-1] + x_i[-1]*.01, mae_usr - mae_usr*.05, 'user')

    path = str('../../rslt/lmdk_sel_eps/' + d)
    # Plot legend
    lmdk_lib.plot_legend()
    # # Show plot
    # plt.show()
    # Save plot
    lmdk_lib.save_plot(path + '-sel-eps.pdf')


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