import sys
from ftplib import FTP
import csv
import os, subprocess
from time import sleep
from config import Config

class Wifi():

	currentIP = ".ip.txt"

	ssid="beamian"
	password="beamiannet2"
	enable=False
	ip=""

	def __init__(self, keepOldConfig = False):

		if not keepOldConfig:
			try:
				os.remove(self.currentIP)
			except OSError:
				pass

		c = Config()
		wifi = c.getWifi()
		if wifi is not None:
			self.ssid     = wifi['ssid']
			self.password = wifi['password']

		# print('Wifi Test configuration:', self.ssid, self.password, self.enable)

	# deprecated
	def readConfigFile(self, filename):
		# with open(filename, 'rb') as csvfile:
		# 	lines = csv.reader(csvfile, delimiter=',')
		# 	lines = filter(None, lines)
		# 	l = lines[0]
		# 	if l != None and l != "":
		# 		return l[0], l[1]
		# 	else:
		# 		return None
		return

	# deprecated
	def writeConfigFile(self, filename, ssid, password):
		# with open(filename, 'wb') as csvfile:
		# 	lines = csv.writer(csvfile, delimiter=',')
		# 	lines.writerow([ssid, password])
		#
		return

	def connect(self, bloking=False):
		if bloking:
			flag = ""
		else:
			flag = " &"

		print("./wpa.sh " + self.ssid + " " + self.password + flag)
		os.system("./wpa.sh " + self.ssid + " " + self.password + flag)
		sleep(1)

	def disconnect(self):
		os.system("./wpa.sh &")
		sleep(1)

	def isConnecting(self):
		return not os.path.isfile(self.currentIP)

	def isConnected(self):
		if not self.isConnecting():
			f = open(self.currentIP, 'rb')
			l = f.read()
			f.close()
			self.ip=l
			if l == '' or l == None:
				self.disconnect()
				return False
			return True
		return False

	def getIp(self):
		return self.ip

	def getIpGateway(self):
		r = subprocess.check_output("ip route list dev wlan0 | awk ' /^default/ {print $3}'", shell=True)
		r = r.split('\n')
		if len(r) > 0:
			return r[0]
		return ''

	def ping(self, ip):
		try:
			response = os.system("ping -c 1 " + ip)
			if response == 0:
				return True
		except:
			pass
		return False

#w=Wifi()
#print(w.ssid)
#print(w.password)

##w.disconnect()
#w.connect()

#while w.isConnecting():
	#print("Waiting")
	#sleep(0.5)

#print('connected')
#print(w.isConnected())

#print('ip')
#print(w.getIp())
