#!/usr/bin/python3
###############################################################
# EumetCastInternet
# gui: select product
# product saved in prod_file
###############################################################
from tkinter import *

import tkinter as tk
import sys,os,getopt
import requests
import threading
import eds_defs
import os
from eds_defs import service_navigator

fn_prod=eds_defs.prod_file
 
# Get and sort product list
def get_prodlist():
  # Retrieve all collections: size refers to the max number of returned results
  collection_parameters = {'_source_include': 'id,abstract', 'size': '500'}
  response = requests.get(service_navigator, params=collection_parameters)

  # check the response (using a function in our data_store_function module)
  ###auth.assert_response(response)

  # build the json format responses into a list
  collection_list = {c['_source']['id']: c['_source']['abstract'] for c in response.json()['hits']['hits']}
  list=[]
  for collection in collection_list:
    list.append(collection)
  list.sort()
  return list

#Setup gui
def setup_gui(collection_list):
  def handle_keypress1(event):
    items = Lb.get(Lb.curselection())
    fp=open(fn_prod,'w')
    fp.write(items + '\n')
    fp.close()
    lab2.delete(0,END)
    lab2.insert(0,items)

  def handle_keypress2(event):
    items = Lb.get(Lb.curselection())
    fp=open(fn_prod,'a')
    fp.write(items+ '\n')
    fp.close()
    lab2.delete(0,END)
    lab2.insert(0,items)

  wnd = tk.Tk()
  frame = Frame(wnd)
  scrollbar = Scrollbar(frame, orient=VERTICAL)
  Lb = Listbox(wnd, yscrollcommand=scrollbar.set)
  scrollbar.config(command=Lb.yview)
  scrollbar.pack(side=RIGHT, fill=Y)


  #################################################################################
  prd=""
  lab1=tk.Label(text="Product file: " + fn_prod)
  lab1.pack(side=tk.TOP,fill="x")

  lab2=tk.Entry()
  if os.path.isfile(fn_prod):
    fp=open(fn_prod,'r')
    prd=fp.readline().rstrip(' \n')
    fp.close()
    lab2.insert(0,prd)
  lab2.pack(side=tk.TOP,fill="x")

  but1=tk.Button(text="Change product")
  but1.bind("<Button-1>",handle_keypress1)
  but1.pack(side=tk.TOP,fill="x")

  but2=tk.Button(text="Add product")
  but2.bind("<Button-1>",handle_keypress2)
  but2.pack(side=tk.TOP,fill="x")

  but3=tk.Button(text="Quit",command=quit)
  but3.pack(side=tk.TOP,fill="x")

  for collection in collection_list:
    Lb.insert(END, collection)
  Lb.pack(side=LEFT, fill=BOTH, expand=1)

  wnd.mainloop()

def main(argv):
#  try:
#    opts, args = getopt.getopt(argv,"sh")
#  except getopt.GetoptError:
#    print "Error: options:"
#    usage()
#    sys.exit(2)

  collection_list=get_prodlist()
  wnd=setup_gui(collection_list)


if __name__ == "__main__":
  main(sys.argv[1:])

