'''
Copyright © 2022 – WildGate Consultancy Solutions Limited – all Rights Reserved


For use only with SecureMapView and only under explicit licence with SecureMapView
Other use can be considered on request, contact WildGate Consultancy Solutions Limited via
www.securemapview.co.uk   or   email    info@wildgate.co.uk

GeoJson Track Generator.  CReates defined number of tracks, within bounded region , tracks update at defined rate


'''
import json
from geojson import Point, Feature, FeatureCollection, dump
from time import sleep

##  define / set initial variables

#####  SETUP ALL VARIABLES  ##################

##  find config file location

delaytime = 1
verbose = 1
TxtLocFile = '/var/www/wildgate.org/public_html/DashDriver/newfile.txt'
JsonLocFile = '/var/www/wildgate.org/public_html/DashMap1/Location.json'
test= []
prevtest=[]



###      LOcation data order  is  W, S , E , N           ### 

while True:
### Read configs from json file
    #try:
    with open(TxtLocFile) as data:
        test = data.readline()  ## use 'load' , not 'loads'
        data.close()
    #except:
      #  print('not able to read newfile.txt')
 
    if  ( test!=prevtest and test!=[]):
    
        print("Change detected")
        #print("test is  ",test)
        prevtest=test
        
        Data = test.split(',')
        
        print(test)
        

        length =len(Data)

###      LOcation data order  is  W, S , E , N           ### 
###            Lofcation.json exepects w,e,n,s      ###

        if length == 4:
            nwlon=(Data[0])  #nwlon is WEST
            print ("swlong is--", nwlon)

            selon=(Data[2])  #selon is EAST
            print ("nelong is--", selon)
            
            nwlat=(Data[3])  #nwlat is NORTH
            print ("swlat is--", nwlat)
            

            selat=(Data[1])  #selat is SOUTH
            print ("nelat is--", selat)

            data = []  
            #data['Loc'] = []  
            #data['Loc'].append({  
            data.append({
                'W':nwlon,
                'E':selon,
                'N':nwlat,
                'S':selat,
                })
            print (data)
            newdata = json.dumps(data)
            print (newdata)


    with open(JsonLocFile, 'w') as outfile:
        outfile.write(newdata)
        print ("outputting to ", JsonLocFile )
        outfile.close()


 #   with open(JsonLocFile, 'w') as outfile:
 #       json.dump(newdata, outfile)
 #       print ("outputting to ", JsonLocFile )
 #       outfile.close()
       
    #except:
    #    print('not able to write Location.json')         
           
    if verbose == 1:
        #print ("outputting to GeoJson")
        print("")       
    if verbose > 1:
        print (update)
        print("")

    sleep(delaytime)
