from otree.api import *
from otree.api import Page, widgets
from otree.api import Currency as c

doc = """
Your app description
"""

# Models

class Constants(BaseConstants):
    name_in_url = 'surveyapp'
    players_per_group = None
    num_rounds = 1

class Subsession(BaseSubsession):
    def creating_session(self):
        num_participants = len(self.get_players())
        num_treatment_groups = 3

        # Calculate the number of participants per treatment group
        participants_per_group = num_participants // (num_treatment_groups + 1)
        remaining_participants = num_participants % (num_treatment_groups + 1)

        # Assign participants to the control group
        control_group = self.get_players()[:participants_per_group]

        # Assign remaining participants to the treatment groups
        treatment_groups = [self.get_players()[i:i + participants_per_group] for i in range(participants_per_group, num_participants, participants_per_group)]

        # Set group matrix
        self.set_group_matrix([control_group] + treatment_groups)

        # Print for debugging
        print("Control Group:")
        for player in control_group:
            print(f"Participant {player.participant.label} treatment group: {player.treatment_group}")

        print("Treatment Groups:")
        for i, group in enumerate(self.get_groups()):
            for player in group.get_players():
                print(f"Participant {player.participant.label} treatment group: {player.treatment_group}")

class Group(BaseGroup):
    pass

class Player(BasePlayer):
    participation_decision = models.StringField(
        choices=['agree', 'disagree'],
        label='Do you agree to participate?',
        initial='agree'
    )
    reconfirm_checkbox = models.BooleanField(
        label='I reconfirm my choice.',
    )

    ambition_level = models.IntegerField(
        label='Choose your level of ambition:',
        choices=[
            [1, '1 - Not at all ambitious'],
            [2, '2'],
            [3, '3'],
            [4, '4'],
            [5, '5'],
            [6, '6 - Extremely ambitious'],
            [7, 'Other'],
        ],
        widget=widgets.RadioSelect,
    )

    other_text = models.StringField(
        label='If you selected "Other," please specify:',
        blank=True,  # Allows leaving the field empty
    )

    purchase_decision = models.StringField(
        label="Please confirm your purchase decision:",
        choices=[
            ["confirm", "I confirm that I wish to purchase Trip x at the price of price of trip x tokens"],
            ["reconsider", "I wish to reconsider my purchase decision."],
        ],
        widget=widgets.RadioSelect,
    )

    offset_carbon = models.StringField(
        label="Please select one of the following:",
        choices=[
            ["yes", "Yes, I wish to offset my carbon emissions from this trip."],
            ["no", "No, I do not wish to offset my carbon emissions from this trip."],
        ],
        widget=widgets.RadioSelect,
    )

    treatment_group = models.StringField()

# PAGES
class Introduction(Page):
    def is_displayed(self):
        return self.round_number == 1

    def before_next_page(self, timeout_happened):
        # Set the treatment group for each player
        if self.group.id_in_subsession == 1:
            self.treatment_group = 'Control Group'
        else:
            self.treatment_group = f'Treatment Group {self.group.id_in_subsession - 1}'

class Information(Page):
    pass

class WhichGroup(Page):
    def vars_for_template(self):
        return {'treatment_group': self.treatment_group}

class ConsentForm(Page):
    form_model = 'player'
    form_fields = ['participation_decision', 'reconfirm_checkbox']

    def js_vars(self):
        return dict(participation_decision=self.participation_decision)

    def live_method(self, data):
        if data['participation_decision'] == 'disagree':
            return dict(redir='EndOfSurvey.html')

class TaskInstructions(Page):
    pass

class BotConf(Page):
    form_model = 'player'
    form_fields = ['ambition_level', 'other_text']


class Trips_C(Page):
    def is_displayed(self):
        return self.treatment_group == 'Control Group'

class PurchaseDecision(Page):
    def is_displayed(self):
        return self.treatment_group == 'Control Group'

class PurchaseSummary(Page):
    form_model = 'player'
    form_fields = ['purchase_decision']

    def is_displayed(self):
        return self.treatment_group == 'Control Group'

class CarbonEmissions(Page):
    form_model = 'player'
    form_fields = ['offset_carbon']

    def is_displayed(self):
        return self.treatment_group == 'Control Group'

class Trips_T1_T2(Page):
    def is_displayed(self):
        return self.treatment_group in ['Treatment Group 1', 'Treatment Group 2']

class PurchaseSummary_T1_T2(Page):
    form_model = 'player'
    form_fields = ['purchase_decision']

    def is_displayed(self):
        return self.treatment_group in ['Treatment Group 1', 'Treatment Group 2']

class CarbonEmissions_T2(Page):
    form_model = 'player'
    form_fields = ['offset_carbon']

    def is_displayed(self):
        return self.treatment_group == 'Treatment Group 2'

class InfoCarbonEmissions_T3(Page):
    def is_displayed(self):
        return self.treatment_group == 'Treatment Group 3'

class Trips_T3(Page):
    def is_displayed(self):
        return self.treatment_group == 'Treatment Group 3'

class PurchaseSummary_T3(Page):
    form_model = 'player'
    form_fields = ['purchase_decision']

    def is_displayed(self):
        return self.treatment_group == 'Treatment Group 3'

class Lottery(Page):
    pass

class CompletitionPage(Page):
    pass

class EndOfSurvey(Page):
    def is_displayed(self):
        return self.participation_decision == 'disagree' and not self.reconfirm_checkbox

    def before_next_page(self, timeout_happened):
        if not self.reconfirm_checkbox:
            self.payoff = 0

page_sequence = [Introduction, Information, WhichGroup, ConsentForm, TaskInstructions, BotConf,
                 PurchaseDecision, Trips_C, PurchaseSummary,
                 CarbonEmissions, Trips_T1_T2, PurchaseSummary_T1_T2,
                 CarbonEmissions_T2, InfoCarbonEmissions_T3, Trips_T3,
                 Lottery, CompletitionPage,EndOfSurvey]