from django.shortcuts import render, redirect
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Survey
from django.contrib import messages
from .tips import TIPS_MAPPING  # Assuming this is where you store your tips

class SurveyView(View):
    template_name = 'survey/survey_form.html'
    success_template = 'survey/survey_tips.html'

    def get(self, request):
        """
        Render the survey form. No login required for viewing the form.
        """
        return render(request, self.template_name)

    def post(self, request):
        """
        Process the survey form and generate tips. Login is required for submitting the form.
        """
        if not request.user.is_authenticated:
            messages.error(request, "You must be logged in to submit the survey.")
            return render(request, self.template_name)

        # Extract data from the form
        data = {
            'user': request.user,
            'water_usage': request.POST.get('dailyWaterUsage'),
            'daily_consumption_awareness': request.POST.get('householdWater'),
            'dripping_tap_wastage': request.POST.get('drippingTap'),
            'brushing_habits': request.POST.get('tapWhileBrushing'),
            'fix_leaks': request.POST.get('fixLeaks'),
            'reuse_water': request.POST.get('reuseWater'),
            'water_saving_appliances': request.POST.get('waterAppliances'),
            'biggest_cause_of_wastage': request.POST.get('waterWastageCause'),
            'resources_needed': request.POST.get('conservationResources'),
            'additional_suggestions': request.POST.get('conservationSuggestions'),
        }

        try:
            # Generate tips
            tips = [
                TIPS_MAPPING['water_usage'].get(data['water_usage'], ""),
                TIPS_MAPPING['dripping_tap_wastage'].get(data['dripping_tap_wastage'], ""),
                TIPS_MAPPING['reuse_water'].get(data['reuse_water'], ""),
                TIPS_MAPPING['water_saving_appliances'].get(data['water_saving_appliances'], ""),
            ]

            # Remove empty tips
            tips = [tip for tip in tips if tip]

            # Save survey
            survey = Survey.objects.create(**data)

            # Render success template with tips
            context = {'survey': survey, 'tips': tips}
            return render(request, self.success_template, context)
        except Exception as e:
            messages.error(request, f"Error: {str(e)}")
            return render(request, self.template_name, {'data': data})



def index(request):
    context = {
        }
    return render(request, 'survey/index.html', context)
