from datetime import datetime
from django.shortcuts import render
from django.http import HttpRequest
from django.contrib.auth.decorators import login_required, permission_required
from TRG.Programs import FireConditions
from TRG.Programs import NOAA
from TRG.Programs import FireData
from TRG.Programs import CriticalValues
from TRG.Programs import GetFires
from TRG.Programs import AQI
from TRG.Programs import LargeFires
import psycopg2
from NEWAFireInfo.settings import DATABASES


@login_required(login_url="/login")
@permission_required('TRG.view_page',login_url="/login")
def report(request):
    """Renders the about page."""
    assert isinstance(request, HttpRequest)

    dbstring = DATABASES['default']
    con = psycopg2.connect(
        host=dbstring['HOST'],
        port=dbstring['PORT'],
        database=dbstring['NAME'],
        user=dbstring['USER'],
        password=dbstring['PASSWORD'])
    cur = con.cursor()

    userid=request.user.id
    if request.method == 'POST':
        if request.user.has_perm('TRG.view_manager') == True:
            override = request.POST.get('reporttype')
            if override == '2':
                override = '0'
                primarysite = request.POST.get('primarysite')
                siteradius = request.POST.get('siteradius')
                aqisensor = request.POST.get('aqisensor')
                cur.execute("SELECT * FROM trg_sites WHERE id=" + str(primarysite))
                psite=cur.fetchone()

                if request.POST.get('allifplzones') == 'on':
                    fc = ['678 E', '678 W', '684', '685', '686', '687', '688']
                else:
                    fc = []
                    if request.POST.get('ifpl678E') == 'on':
                        fc = fc + ['678 E']
                    if request.POST.get('ifpl678W') == 'on':
                        fc = fc + ['678 W']
                    if request.POST.get('ifpl684') == 'on':
                        fc = fc + ['684']
                    if request.POST.get('ifpl685') == 'on':
                        fc = fc + ['685']
                    if request.POST.get('ifpl686') == 'on':
                        fc = fc + ['686']
                    if request.POST.get('ifpl687') == 'on':
                        fc = fc + ['687']
                    if request.POST.get('ifpl688') == 'on':
                        fc = fc + ['688']
                    if fc == []:
                        fc = [9]
                if request.POST.get('allfires') == 'on':
                    allfires = 1
                else:
                    allfires = 0

                if request.POST.get('alltas') == 'on':
                    kmllist = ['TA Bartlette Meadows.kml','TA Drummond Creek.kml','TA Flodelle.kml','TA Jackknife.kml','TA Muddy.kml','TA Sherman Creek.kml','TA Tacoma.kml']
                else:
                    kmllist = []
                    if request.POST.get('bartlette') == 'on':
                        kmllist = kmllist + ['TA Bartlette Meadows.kml']
                    if request.POST.get('drummond') == 'on':
                        kmllist = kmllist + ['TA Drummond Creek.kml']
                    if request.POST.get('flodelle') == 'on':
                        kmllist = kmllist + ['TA Flodelle.kml']
                    if request.POST.get('jackknife') == 'on':
                        kmllist = kmllist + ['TA Jackknife.kml']
                    if request.POST.get('muddy') == 'on':
                        kmllist = kmllist + ['TA Muddy.kml']
                    if request.POST.get('sherman') == 'on':
                        kmllist = kmllist + ['TA Sherman Creek.kml']
                    if request.POST.get('tacoma') == 'on':
                        kmllist = kmllist + ['TA Tacoma.kml']
                    if kmllist == []:
                        kmllist =[9]
                cur.execute("SELECT userid FROM trg_manager_settings WHERE userid=" + str(userid))
                checkexists=cur.fetchone()
                if checkexists == None:
                    cur.execute("INSERT INTO trg_manager_settings (userid, siteid, radius, aqisensor, ifpl_zones, allfires, tngareas, siteids) VALUES ("+str(userid)+","+ str(primarysite) +"," + str(siteradius) + ","+ str(aqisensor) +", ARRAY"+str(fc)+","+str(allfires)+", ARRAY"+str(kmllist)+",ARRAY"+str([1])+")")
                else:
                    cur.execute("DELETE FROM trg_manager_settings WHERE userid=" + str(userid))
                    cur.execute("INSERT INTO trg_manager_settings (userid, siteid, radius, aqisensor, ifpl_zones, allfires, tngareas, siteids) VALUES ("+str(userid)+","+ str(primarysite) +","+ str(siteradius) +","+ str(aqisensor) +", ARRAY"+str(fc)+","+str(allfires)+", ARRAY"+str(kmllist)+",ARRAY"+str([1])+")")
                # SET SAVE and GET REPORT VARIABLES HERE
                add = True
                if fc[0] == 9:
                    fc = [psite[4]]
                else:
                    temp = []
                    for i in range(len(fc)):
                        if fc[i].find(psite[4]) != -1:
                            add = False
                    if add == True:
                        temp = [psite[4]]+fc
                    else:
                        temp = fc
                    fc = temp

                add = True
                if kmllist[0] == 9:
                    kmllist = [psite[6]]
                else:
                    temp = []
                    for i in range(len(kmllist)):
                        if kmllist[i].find(psite[6]) != -1:
                            add = False
                    if add == True:
                        temp = [psite[6]]+kmllist
                    else:
                        temp = kmllist
                    kmllist = temp

                userloc = [psite[2],psite[3]]

            else:
                cur.execute("SELECT * FROM trg_manager_settings JOIN trg_sites ON trg_manager_settings.siteid = trg_sites.id WHERE userid=" + str(userid))
                string = cur.fetchone()
                add = True
                fc=[]
                if string[4][0] == '9':
                    fc = [string[12]]
                else:
                    for i in range(len(string[4])):
                        if string[4][i].find(string[12]) != -1:
                            add = False
                    if add == True:
                        fc = [string[12]]+string[4]
                    else:
                        fc = string[4]
                allfires = string[5]
                add = True
                kmllist=[]
                if string[6][0] == '9':
                    kmllist = [string[14]]
                else:
                    for i in range(len(string[6])):
                        if string[6][i].find(string[14]) != -1:
                            add = False
                    if add == True:
                        kmllist = [string[14]]+string[6]
                    else:
                        kmllist = string[6]
                userloc = [string[10], string[11]]
                
        elif request.user.has_perm('TRG.view_page')==True:
            primarysite = request.POST.get('primarysite')
            siteradius = request.POST.get('siteradius')
            aqisensor = request.POST.get('aqisensor')
            cur.execute("SELECT userid FROM trg_member_settings WHERE userid=" + str(userid))
            checkexists=cur.fetchone()
            if checkexists == None:
                cur.execute("INSERT INTO trg_member_settings (userid, siteid, radius, aqisensor) VALUES ("+str(userid)+","+ str(primarysite) +"," + str(siteradius) + ","+ str(aqisensor) +")")
            else:
                cur.execute("DELETE FROM trg_member_settings WHERE userid=" + str(userid))
                cur.execute("INSERT INTO trg_member_settings (userid, siteid, radius, aqisensor) VALUES ("+str(userid)+","+ str(primarysite) +","+ str(siteradius) +","+ str(aqisensor) +")")
            cur.execute("SELECT * FROM trg_member_settings JOIN trg_sites ON trg_member_settings.siteid = trg_sites.id WHERE userid=" + str(userid))
            string = cur.fetchone()
            allfires = 0
            override = '0'
            kmllist = [string[10]]
            userloc = [string[6],string[7]]
            fc = [string[8]]
            
        con.commit()
    else:
        if request.user.has_perm('TRG.view_page')==True:
            override = '0'
            cur.execute("SELECT * FROM trg_member_settings JOIN trg_sites ON trg_member_settings.siteid = trg_sites.id WHERE userid=" + str(userid))
            string = cur.fetchone()
            fc = [string[8]]
            kmllist = [string[10]]
            userloc = [string[6],string[7]]
            allfires = 0

    fireconditions = FireConditions.main(fc)
    try:
        aqi = AQI.main(userloc)
        aqidown = ''
    except:
        aqidown = ' - The EPA AQI site interface is currently down.'
        aqi=''
        pass
    if FireData.checkdates() == False:
        try:
            FireData.main()
        except:
            pass    
        FireData.main()

    try:
        criticaldata = CriticalValues.main()
    except:
        criticaldata = ''
        pass
    
    if allfires == 0 and kmllist == []:
        fires = ''
        pass
    else:
        try:
            fires = GetFires.main(allfires, kmllist, override)
        except:
            fires = []
            pass
    try:
        weather = NOAA.main(userloc)
        weatherdown = ''
    except:
        weatherdown = '- The NOAA weather for this location is currently unavailable.'
        weather = ''
        pass
    con.close()
    return render(
        request,
        'TRG/report.html',
        {
            'title':'Report',
            'menureport':'active',
            'message':'Your application description page.',
            'year':datetime.now().year,
            'fireconditions':fireconditions,
            'weather':weather,
            'weatherdown':weatherdown,
            'criticaldata':criticaldata,
            'fires':fires,
            'aqi':aqi,
            'age':LargeFires.checkage(),
            'aqidown':aqidown
        }
    )

@permission_required('TRG.view_page',login_url="/login")
@login_required(login_url="/login")
def settings(request):
    assert isinstance(request, HttpRequest)
    dbstring = DATABASES['default']
    con = psycopg2.connect(
        host=dbstring['HOST'],
        port=dbstring['PORT'],
        database=dbstring['NAME'],
        user=dbstring['USER'],
        password=dbstring['PASSWORD'])
    cur = con.cursor()

    if request.user.has_perm('TRG.view_manager') == True:
        cur.execute("SELECT * FROM trg_sites WHERE id=1")
        psite = []
        psite = psite + [cur.fetchone()]
        cur.execute("SELECT * FROM trg_sites WHERE id=2")
        psite = psite + [cur.fetchone()]
        cur.execute("SELECT * FROM trg_sites WHERE id!=1 AND id!=2 ORDER BY name")
        temp =cur.fetchall()
        for i in range(len(temp)):
            psite = psite + [temp[i]]





    elif request.user.has_perm('TRG.view_page')==True:
        cur.execute("SELECT * FROM trg_sites WHERE id=1")
        psite = []
        psite = psite + [cur.fetchone()]
        cur.execute("SELECT * FROM trg_sites WHERE id=2")
        psite = psite + [cur.fetchone()]
        cur.execute("SELECT * FROM trg_sites WHERE id!=1 AND id!=2 ORDER BY name")
        temp =cur.fetchall()
        for i in range(len(temp)):
            psite = psite + [temp[i]]


    con.close()
    return render(
        request,
        'TRG/settings.html',
        {
            'title':'This Page is Under Construction',
            'menureport':'active',
            'year':datetime.now().year,
            'age':LargeFires.checkage(),
            'psite':psite,
        }
        
    )
