# -*- coding: utf-8 -*-

import os
import numpy as np
import matplotlib.pyplot as plt
import pdb
import ee

import matplotlib.dates as mdates
import matplotlib.cm as cm
from datetime import datetime, timedelta
import pickle
import pytz
import scipy.io as sio
import scipy.interpolate as interpolate
import statsmodels.api as sm
import skimage.measure as measure


# my functions
import functions.utils as utils
import functions.sds as sds

# some settings
np.seterr(all='ignore') # raise/ignore divisions by 0 and nans
plt.rcParams['axes.grid'] = True
plt.rcParams['figure.max_open_warning'] = 100

au_tz = pytz.timezone('Australia/Sydney')

# load timestamps from satellite images
satname = 'L8'
sitename = 'OLDBAR'
filepath = os.path.join(os.getcwd(), 'data', satname, sitename)
with open(os.path.join(filepath, sitename + '_output' + '.pkl'), 'rb') as f:
    output = pickle.load(f)
dates_l8 = output['t']
# convert to AEST
dates_l8 = [_.astimezone(au_tz) for _ in dates_l8]
# get the satellite shorelines
sl = output['shorelines']

# load narrabeen beach points (manually digitized)
with open(os.path.join(os.getcwd(), 'olddata', 'oldbar_beach' + '.pkl'), 'rb') as f:
    narrabeach = pickle.load(f)
    

dist_thresh = 250
frac_smooth = 1./12
plt.figure()
plt.axis('equal')
for i in range(1):
    # select point of sds that are close to the manually digitized points
    idx_beach = [np.min(np.linalg.norm(sl[i][k,:] - narrabeach, axis=1)) < dist_thresh for k in range(sl[i].shape[0])]
    plt.plot(sl[i][:,0], sl[i][:,1])
    plt.plot(sl[i][idx_beach,0], sl[i][idx_beach,1])


    # smooth (LOWESS) satellite shoreline    
    sl_smooth = sm.nonparametric.lowess(sl[i][idx_beach,0],sl[i][idx_beach,1], frac=frac_smooth, it = 10)
    sl_smooth = sl_smooth[:,[1,0]]
    
    plt.plot(sl_smooth[:,0], sl_smooth[:,1])

    
plt.draw()   
