from flask import Flask, render_template, request, redirect, url_for
from flask_navigation import Navigation
from Webserver.Translater import Translater, Language


class Webserver:
    def __init__(self, zoneManager, port=80):
        self.port = port
        self.zoneManager = zoneManager
        self.translater_EN = Translater(Language.ENGLISH)
        self.translater_DE = Translater(Language.GERMAN)
        self.translater = self.translater_DE

    def startWebserver(self):
        app = Flask("Bewässerungssystem", template_folder="Webserver/templates", static_folder="Webserver/static")
        nav = Navigation(app)

        nav.Bar('top', [
            nav.Item(self.translater.getTranslation('Dashboard'), 'showDashboard'),
            nav.Item(self.translater.getTranslation('irrigation zones'), 'showZones'),
            nav.Item(self.translater.getTranslation('blocking times'), 'showTimes'),
            nav.Item(self.translater.getTranslation('system settings'), 'showSystem')
            # nav.Item('Gfg', 'gfg', {'page': 5}), #(example with pages)
        ])

        # Example Route with pages:
        # @app.route('/gfg/<int:page>')
        # def gfg(page):
        #    return render_template('gfg.html', page=page)

        @app.route('/')
        def startPage():
            return redirect(url_for('showDashboard'))

        @app.route('/action', methods=['GET', 'POST'])
        def executeAction(command=False, index_str=False, value_str=False):
            if(request.method == 'POST'):
                try:
                    command = request.form['command']
                except:
                    pass
                try:
                    index_str = request.form['index']
                    index = int(index_str)
                except:
                    pass
                try:
                    value_str = request.form['value']
                    value = int(value_str)
                except:
                    pass
            elif(request.method == 'GET'):
                try:
                    command = request.args['command']
                except:
                    pass
                try:
                    index_str = request.args['index']
                    index = int(index_str)
                except:
                    pass
                try:
                    value_str = request.args['value']
                    value = int(value_str)
                except:
                    pass
            match command:
                case "switch_zone_on":
                    if (index and value):
                        self.zoneManager.switchZoneIndexState(zoneIndex=index, state=True, duration=value)
                        return "True"
                    elif(index):
                        self.zoneManager.switchZoneIndexState(zoneIndex=index, state=True, duration=self.zoneManager.systemSettings.defaultManualIrrigationDuration)
                        return "True"
                case "switch_zone_off":
                    if (index and value):
                        self.zoneManager.switchZoneIndexState(zoneIndex=index, state=False, duration=value, instant=True)
                        return "True"
                    elif(index):
                        self.zoneManager.switchZoneIndexState(zoneIndex=index, state=False, duration=self.zoneManager.systemSettings.defaultManualOffDuration, instant=True)
                        return "True"
                case "switch_zone_mode":
                    zonesToSwitch = []
                    if(index_str == "all" and value_str):
                        zonesToSwitch = self.zoneManager.zones
                    elif (index and value_str):
                        zonesToSwitch.append(self.zoneManager.getZone(index))
                    else:
                        return "False"
                    automode = False
                    if(value_str == "automatic"):
                        automode = True
                    elif(value_str == "manual"):
                        automode = False
                    else:
                        return "False"
                    for zone in zonesToSwitch:
                        zone.switchMode(autoMode=automode)
                    return "True"
                case "set_desired_humidity":
                    if (index and value):
                        zone = self.zoneManager.getZone(index)
                        zone.desiredHumidity = value
                        return "True"
                case "delete_jobs_for_zone":
                    if (index):
                        zone = self.zoneManager.getZone(index)
                        self.zoneManager.deleteIrrigationJobsForZone(zone)
                        return "True"
                case "delete_job_by_id":
                    if(index_str == "all"):
                        self.zoneManager.clearIrrigationJobs()
                        return "True"
                    if (index):
                        self.zoneManager.deleteIrrigationJobByID(index)
                        return "True"
                case "get_dashboard_zone_html":
                    if (index):
                        zone = self.zoneManager.getZone(index)
                        return render_template('dashboard/zone.html', translater=self.translater, zoneManager=self.zoneManager, zone=zone)
                case "get_dashboard_pipeline_html":
                    return render_template("dashboard/pipeline.html", translater=self.translater, zoneManager=self.zoneManager)
                case "get_zone_list":
                    return self.zoneManager.zonesToJSON(self.translater)
                case "get_zone_info":
                    if (index):
                        zone = self.zoneManager.getZone(index)
                        return zone.toJSON(self.translater)
                case "get_pipeline":
                    return self.zoneManager.pipelineToJSON(self.translater)
            return "False"


        @app.route('/dashboard')
        def showDashboard():
            return render_template('dashboard/dashboard.html', translater=self.translater, zoneManager=self.zoneManager)

        @app.route('/zones')
        @app.route('/zones/<zoneNumber>')
        def showZones(zoneNumber=False):
            if (zoneNumber):
                return render_template('zones/zone.html', translater=self.translater, zoneManager=self.zoneManager, zone=self.zoneManager.getZone(zoneNumber))
            else:
                return render_template('zones/zones.html', translater=self.translater, zoneManager=self.zoneManager)

        @app.route('/times')
        def showTimes():
            return render_template('times.html', translater=self.translater, zoneManager=self.zoneManager)

        @app.route('/system')
        def showSystem():
            return render_template('system.html', translater=self.translater, zoneManager=self.zoneManager)

        app.run(debug=True, host="0.0.0.0", port=self.port)
