import configparser as cp
import os
import numpy as np
import csv
import h5py
import matplotlib.pyplot as plt

from debug.outliers import outliers
from debug.friction import truncated_friction
from debug.state import aging_law
from debug.diffplot import diffplot

from support.maximum import maximum
from support.norm import norm
from support.find_quakes import find_quakes
from support.slip_beginnings import slip_beginnings
from support.slip_endings import slip_endings
from support.max_distance import max_distance

from support.io import read_h5file

from support.iterations import iterations
from support.friction_stats import friction_stats
from support.slip_rates import slip_rates

def build_patch(coords, percentage):
    x_coords = coords[:, 0]
    xmin = np.min(x_coords)
    xmax = np.max(x_coords)
    delta_x = (1 - percentage)*(xmax - xmin)/2

    xmin = xmin + delta_x
    xmax = xmax - delta_x

    return [i for i in range(len(x_coords)) if x_coords[i]>=xmin and x_coords[i]<=xmax]


NBODIES = 2
FINAL_TIME = 15  # s
FINAL_VELOCITY = 2e-4  # m/s
THRESHOLD_VELOCITY = 0.5*FINAL_VELOCITY  # 1000e-6 + FINAL_VELOCITY

TANGENTIAL_COORDS = 1

# friction params
params = {
    'L'  : 1e-5,
    'V0' : 1e-6,
    'mu0': 0.6,
    'a'  : 0.010,
    'b'  : 0.015
}

h5file = read_h5file()
print(list(h5file.keys()))

interval = [10, 13] #[0.75*FINAL_TIME, FINAL_TIME]

iterations(h5file, FINAL_TIME, interval)

for body_ID in range(NBODIES):
    body = 'body' + str(body_ID)

    if body not in h5file:
        continue

    coords = np.array(h5file[body + '/coordinates'])
    patch = build_patch(coords, 1.0)

    friction_stats(h5file, body_ID, FINAL_TIME, patch, interval)
    slip_rates(h5file, body_ID, FINAL_TIME, patch, interval, 0)

plt.show()

h5file.close()