# -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 17:12:35 2018

@author: Kilian
"""

# Initial settings
import os
import numpy as np
import matplotlib.pyplot as plt
import ee
import pdb

# other modules
from osgeo import gdal, ogr, osr
import pickle
import matplotlib.cm as cm
from pylab import ginput

# image processing modules
import skimage.filters as filters 
import skimage.exposure as exposure
import skimage.transform as transform
import sklearn.decomposition as decomposition
import skimage.measure as measure


# import own modules
import functions.utils as utils
import functions.sds as sds

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

# initial settings
cloud_thresh = 0.5      # threshold for cloud cover
plot_bool = False       # if you want the plots
prob_high = 99.9        # upper probability to clip and rescale pixel intensity
min_contour_points = 100# minimum number of points contained in each water line
output_epsg = 28356     # GDA94 / MGA Zone 56

satname = 'L7'
sitename = 'NARRA'
filepath = os.path.join(os.getcwd(), 'data', satname, sitename)
with open(os.path.join(filepath, sitename + '_timestamps' + '.pkl'), 'rb') as f:
    timestamps = pickle.load(f)
timestamps_sorted = sorted(timestamps)
with open(os.path.join(filepath, sitename + '_epsgcode' + '.pkl'), 'rb') as f:
    input_epsg = pickle.load(f)
    
file_path_pan = os.path.join(filepath, 'pan')
file_path_ms = os.path.join(filepath, 'ms')
file_names_pan = os.listdir(file_path_pan)
file_names_ms = os.listdir(file_path_ms)
N = len(file_names_pan)
idx_high_cloud = []
t = []
shorelines = []

for i in range(N):
    # read pan image
    fn_pan = os.path.join(file_path_pan, file_names_pan[i])
    data = gdal.Open(fn_pan, gdal.GA_ReadOnly)
    georef = np.array(data.GetGeoTransform())
    bands = [data.GetRasterBand(i + 1).ReadAsArray() for i in range(data.RasterCount)]
    im_pan = np.stack(bands, 2)[:,:,0]
    # read ms image
    fn_ms = os.path.join(file_path_ms, file_names_ms[i])
    data = gdal.Open(fn_ms, gdal.GA_ReadOnly)
    bands = [data.GetRasterBand(i + 1).ReadAsArray() for i in range(data.RasterCount)]
    im_ms = np.stack(bands, 2)
    
