# Path: tethysapp/erfp_tool/model.py
# class MainSettings(Base):
# class BaseLayer(Base):
# class DataStore(Base):
# class DataStoreType(Base):
# class Geoserver(Base):
# class Watershed(Base):
# class WatershedWatershedGroupLink(Base):
# class WatershedGroup(Base):
#     def __init__(self, base_layer_id, ecmwf_rapid_prediction_directory, default_group_id,
#                  era_interim_rapid_directory, wrf_hydro_rapid_prediction_directory):
#     def __init__(self, name, api_key):
#     def __init__(self, server_name, data_store_type_id, api_endpoint, api_key):
#     def __init__(self, code_name, human_readable_name):
#     def __init__(self, name, url, username, password):
#     def __init__(self, watershed_name, subbasin_name, folder_name, file_name,
#                  data_store_id, ecmwf_rapid_input_resource_id, 
#                  ecmwf_data_store_watershed_name, ecmwf_data_store_subbasin_name,
#                  wrf_hydro_data_store_watershed_name, wrf_hydro_data_store_subbasin_name,
#                  geoserver_id, geoserver_drainage_line_layer, geoserver_catchment_layer, 
#                  geoserver_gage_layer, geoserver_ahps_station_layer, geoserver_outline_layer,
#                  geoserver_drainage_line_uploaded, geoserver_catchment_uploaded, 
#                  geoserver_gage_uploaded, geoserver_ahps_station_uploaded, geoserver_outline_uploaded,
#                  kml_drainage_line_layer, kml_catchment_layer, kml_gage_layer):
#     def __init__(self, name):
# 
# Path: tethysapp/erfp_tool/functions.py
# def format_name(string):
#     """
#     Formats watershed name for code
#     """
#     if string:
#         formatted_string = string.strip().replace(" ", "_").lower()
#         formatted_string = re.sub(r'[^a-zA-Z0-9_-]', '', formatted_string)
#         while formatted_string.startswith("-") or formatted_string.startswith("_"):
#             formatted_string = formatted_string[1:]
#     else:
#         formatted_string = ""
#     return formatted_string
# 
# def format_watershed_title(watershed, subbasin):
#     """
#     Formats title for watershed in navigation
#     """
#     max_length = 30
#     watershed = watershed.strip()
#     subbasin = subbasin.strip()
#     watershed_length = len(watershed)
#     if(watershed_length>max_length):
#         return watershed[:max_length-1].strip() + "..."
#     max_length -= watershed_length
#     subbasin_length = len(subbasin)
#     if(subbasin_length>max_length):
#         return (watershed + " (" + subbasin[:max_length-3].strip() + " ...)")
#     return (watershed + " (" + subbasin + ")")
# 
# def user_permission_test(user):
#     """
#     User needs to be superuser or staff
#     """
#     return user.is_superuser or user.is_staff
# 
# def get_watershed_info(app_instance_id, session, watersheds_group):
#     # maybe make this one list?
#     #list of names and ids in group for dropdown list
#     dropdown_watershed_list = []
#     for watershed in watersheds_group:
#         dropdown_watershed_list.append(("%s (%s)" % (watershed.watershed_name, watershed.subbasin_name),
#                                watershed.id))
#     outline_watersheds_list = []
#     #list of names, geoservers, app_id, ids for loading outlines
#     for watershed in watersheds_group:
#         geoserver = session.query(Geoserver).filter(Geoserver.id == watershed.geoserver_id).all()[0]
#         geoserver_url = geoserver.url
#         outline_watersheds_list.append(
#             [watershed.ecmwf_data_store_watershed_name, geoserver_url, watershed.id, watershed.geoserver_outline_layer])
# 
#     return outline_watersheds_list, dropdown_watershed_list


import json
import os
from datetime import datetime, timedelta
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import redirect, render
from tethys_dataset_services.engines import GeoServerSpatialDatasetEngine
from .model import (BaseLayer, DataStore, DataStoreType, Geoserver, MainSettings,
                    SettingsSessionMaker, Watershed, WatershedGroup)
from .functions import (format_name, format_watershed_title, 
                        user_permission_test, get_watershed_info)
from tethys_sdk.gizmos import MapView, MVView, MVLayer, MVLegendClass

@user_passes_test(user_permission_test)
def manage_watersheds(request):        
    """
    Controller for the app manage_watersheds page.
    """
    #initialize session
    session = SettingsSessionMaker()
    num_watersheds = session.query(Watershed).count()
    session.close()
    edit_modal = {'name': 'edit_watershed_modal',
               'title': 'Edit Watershed',
               'message': 'Loading ...',
               'dismiss_button': 'Nevermind',
               'affirmative_button': 'Save Changes',
               'width': 500}
    context = {
        'initial_page': 0,
        'num_watersheds': num_watersheds,
        'edit_modal' : edit_modal
    }

    return render(request, 'erfp_tool/manage_watersheds.html', context)

@user_passes_test(user_permission_test)
def manage_watersheds_table(request):
    """
    Controller for the app manage_watersheds page.
    """
    #initialize session

# Path: tethysapp/erfp_tool/model.py
# class MainSettings(Base):
# class BaseLayer(Base):
# class DataStore(Base):
# class DataStoreType(Base):
# class Geoserver(Base):
# class Watershed(Base):
# class WatershedWatershedGroupLink(Base):
# class WatershedGroup(Base):
#     def __init__(self, base_layer_id, ecmwf_rapid_prediction_directory, default_group_id,
#                  era_interim_rapid_directory, wrf_hydro_rapid_prediction_directory):
#     def __init__(self, name, api_key):
#     def __init__(self, server_name, data_store_type_id, api_endpoint, api_key):
#     def __init__(self, code_name, human_readable_name):
#     def __init__(self, name, url, username, password):
#     def __init__(self, watershed_name, subbasin_name, folder_name, file_name,
#                  data_store_id, ecmwf_rapid_input_resource_id, 
#                  ecmwf_data_store_watershed_name, ecmwf_data_store_subbasin_name,
#                  wrf_hydro_data_store_watershed_name, wrf_hydro_data_store_subbasin_name,
#                  geoserver_id, geoserver_drainage_line_layer, geoserver_catchment_layer, 
#                  geoserver_gage_layer, geoserver_ahps_station_layer, geoserver_outline_layer,
#                  geoserver_drainage_line_uploaded, geoserver_catchment_uploaded, 
#                  geoserver_gage_uploaded, geoserver_ahps_station_uploaded, geoserver_outline_uploaded,
#                  kml_drainage_line_layer, kml_catchment_layer, kml_gage_layer):
#     def __init__(self, name):
# 
# Path: tethysapp/erfp_tool/functions.py
# def format_name(string):
#     """
#     Formats watershed name for code
#     """
#     if string:
#         formatted_string = string.strip().replace(" ", "_").lower()
#         formatted_string = re.sub(r'[^a-zA-Z0-9_-]', '', formatted_string)
#         while formatted_string.startswith("-") or formatted_string.startswith("_"):
#             formatted_string = formatted_string[1:]
#     else:
#         formatted_string = ""
#     return formatted_string
# 
# def format_watershed_title(watershed, subbasin):
#     """
#     Formats title for watershed in navigation
#     """
#     max_length = 30
#     watershed = watershed.strip()
#     subbasin = subbasin.strip()
#     watershed_length = len(watershed)
#     if(watershed_length>max_length):
#         return watershed[:max_length-1].strip() + "..."
#     max_length -= watershed_length
#     subbasin_length = len(subbasin)
#     if(subbasin_length>max_length):
#         return (watershed + " (" + subbasin[:max_length-3].strip() + " ...)")
#     return (watershed + " (" + subbasin + ")")
# 
# def user_permission_test(user):
#     """
#     User needs to be superuser or staff
#     """
#     return user.is_superuser or user.is_staff
# 
# def get_watershed_info(app_instance_id, session, watersheds_group):
#     # maybe make this one list?
#     #list of names and ids in group for dropdown list
#     dropdown_watershed_list = []
#     for watershed in watersheds_group:
#         dropdown_watershed_list.append(("%s (%s)" % (watershed.watershed_name, watershed.subbasin_name),
#                                watershed.id))
#     outline_watersheds_list = []
#     #list of names, geoservers, app_id, ids for loading outlines
#     for watershed in watersheds_group:
#         geoserver = session.query(Geoserver).filter(Geoserver.id == watershed.geoserver_id).all()[0]
#         geoserver_url = geoserver.url
#         outline_watersheds_list.append(
#             [watershed.ecmwf_data_store_watershed_name, geoserver_url, watershed.id, watershed.geoserver_outline_layer])
# 
#     return outline_watersheds_list, dropdown_watershed_list


# Path: tethysapp/erfp_tool/controllers.py
import json
import os
from datetime import datetime, timedelta
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import redirect, render
from tethys_dataset_services.engines import GeoServerSpatialDatasetEngine
from .model import (BaseLayer, DataStore, DataStoreType, Geoserver, MainSettings,
                    SettingsSessionMaker, Watershed, WatershedGroup)
from .functions import (format_name, format_watershed_title, 
                        user_permission_test, get_watershed_info)
from tethys_sdk.gizmos import MapView, MVView, MVLayer, MVLegendClass


@user_passes_test(user_permission_test)
def manage_watersheds(request):        
    """
    Controller for the app manage_watersheds page.
    """
    #initialize session
    session = SettingsSessionMaker()
    num_watersheds = session.query(Watershed).count()
    session.close()
    edit_modal = {'name': 'edit_watershed_modal',
               'title': 'Edit Watershed',
               'message': 'Loading ...',
               'dismiss_button': 'Nevermind',
               'affirmative_button': 'Save Changes',
               'width': 500}
    context = {
        'initial_page': 0,
        'num_watersheds': num_watersheds,
        'edit_modal' : edit_modal
    }

    return render(request, 'erfp_tool/manage_watersheds.html', context)

@user_passes_test(user_permission_test)
def manage_watersheds_table(request):
    """
    Controller for the app manage_watersheds page.
    """
    #initialize session

    session = SettingsSessionMaker()