"""
School Year Transition Events
School progression and grade transitions (from dayEvents.py)

Events:
- school: School year transitions and grade progression
- graduate5th: 5th grade graduation
- graduate8th: 8th grade graduation
- graduate12th: 12th grade graduation (high school)
- college: College year transitions
- collegeParty: College party
- collegeGreekLife: Joining Greek life
- collegeMissHome: Missing home in college
- collegeMinor: Choosing a college minor
- adultMissFriends: Missing friends as adult
- driversLessons: Driver's education
- driversTest: Taking driver's test
- positiveInteraction: Positive social interaction
- lowEnergyEvents: Low energy coping mechanisms
- extendedFamily: Extended family relationship events
- murderAttempt: Extreme negative relationship event
- funeral: Attending a funeral
"""

import random
from events.base import messageFunction, questionFunction, answerOption

# Import all functions from dayEvents.py that weren't moved to other categories
# These are primarily school progression events

def school(player, type='message'):
    """School year transitions and grade progression"""
    fname = 'school'
    check = False
    result = False
    message = False
    education = False
    if (player.c.occupation == "student" and 'college' not in player.c.education and player.date == '09-01') or (player.c.occupation == "preschool" and player.c.ageYears >= 4 ): # start new school year
        education = player.c.education
        check = True
        if (player.c.education == 'None' and player.c.ageYears >= 5):
            message = "You have started kindergarten"
            education = 'kindergarten'
        elif (player.c.education == 'kindergarten'):
            player.c.elementary_school = random.choice(player.elementary_schools)
            player.c.activities.append(player.c.elementary_school)
            message = "You have started 1st grade"
            education = '1st'
            from functions import EducationRecord
            player.c.current_education = EducationRecord(educationLevel=education,location=player.c.elementary_school,date=player.date)
            player.c.activityRecords.append(player.c.current_education)
        elif (player.c.education == '1st'):
            message = "You have started 2nd grade"
            education = '2nd'
        elif (player.c.education == '2nd'):
            message = "You have started 3rd grade"
            education = '3rd'
        elif (player.c.education == '3rd'):
            message = "You have started 4th grade"
            education = '4th'
        elif (player.c.education == '4th'):
            message = "You have started 5th grade"
            education = '5th'
        elif (player.c.education == '5th'):
            message = "You have started 6th grade"
            education = '6th'
        elif (player.c.education == '6th'):
            message = "You have started 7th grade"
            education = '7th'
        elif (player.c.education == '7th'):
            message = "You have started 8th grade"
            education = '8th'
        elif (player.c.education == '8th'):
            for a in player.c.activities:
                if (a in player.elementary_schools):
                    player.c.activities.remove(a)
            
            player.c.high_school = random.choice(player.high_schools)
            player.c.activities.append(player.c.high_school)
            from functions import EducationRecord
            player.c.current_education = EducationRecord(educationLevel=education,location=player.c.high_school,date=player.date)
            player.c.activityRecords.append(player.c.current_education)
            message = "You have started highschool"
            education = '9th'
        elif (player.c.education == '9th'):
            message = "You have started 10th grade"
            education = '10th'
        elif (player.c.education == '10th'):
            message = "You have started 11th grade"
            education = '11th'
        elif (player.c.education == '11th'):
            message = "You have started 12th grade"
            education = '12th'
        player.c.occupation = 'student'
        player.c.education = education
        print('education updated to '+education)
    if (player.c.occupation == "student" and 'college' not in player.c.education and player.date == '06-01'): # end school year
        check = True
        if (player.c.education != "highschool" and player.c.education != "college"):
            message = "You have finished "+player.c.education+" grade"
            if (player.c.education == "8th"):
                graduate8th(player)
            if (player.c.education == "5th"):
                graduate5th(player)
        else:
            message = "You have finished school for the year"
            player.dayEvent = "yearlyGraduation"

    result = messageFunction(fname,message,player,check)
    if (result):
        if (player.c.education == 'None'):
            from functions import create_classmates
            create_classmates(player)
        player.updateClient = True
    return result


def graduate5th(player, type='message', message=False, response=False, check=False):
    fname = 'graduate5th'
    result = False
    message = False
    if (player.c.occupation == "student" and player.c.education == '5th' and player.date == '06-01'): # end school year
        check = True
        message = "You have finished 5th grade! Take this opportunity to reflect on your life so far, and say goodbye to your elementary school friends."

    result = questionFunction(fname,message,player,check,["Onward to middle school!"])
    if (result):
        player.updateClient = True
    return result


def graduate8th(player, type='message', message=False, response=False, check=False):
    fname = 'graduate8th'
    result = False
    message = False
    if (player.c.occupation == "student" and player.c.education == '8th' and player.date == '06-01'): # end school year
        check = True
        message = "You have finished 8th grade! Take this opportunity to reflect on your life so far, and say goodbye to your middle school friends."

    result = questionFunction(fname,message,player,check,["Onward to highschool!"])
    if (result):
        player.updateClient = True
    return result


def graduate12th(player, type='message', message=False, response=False, check=False):
    fname = 'graduate12th'
    result = False
    message = False
    if (player.c.occupation == "student" and player.c.education == '12th' and player.date == '06-01'): # end school year
        check = True
        message = "You have finished 12th grade! Take this opportunity to reflect on your life so far, and say goodbye to your high school friends."
        for a in player.c.activities:
                if (a in player.high_schools):
                    player.c.activities.remove(a)
    result = questionFunction(fname,message,player,check,["Onward to college!"])
    if (result):
        player.updateClient = True
    return result


def college(player, type='message'):
    fname = 'college'
    check = False
    result = False
    message = False
    education = False
    if (player.c.occupation == "student" and player.c.college and (player.c.education == "12th" or 'college' in player.c.education ) and player.date == '09-01'): # start new school year
        education = player.c.education
        check = True
        print("starting college year" + player.c.education)
        if (player.c.education == '12th'):
            message = "You have started college at "+player.c.college.title+'! You are a freshman.'
            player.c.job = False
            for a in player.c.activities:
                if a.type == 'job':
                    player.c.activities.remove(a)
            education = 'college yr 1'
            from functions import EducationRecord
            player.c.current_education = EducationRecord(educationLevel=education,location=player.c.college,date=player.date)
            player.c.activityRecords.append(player.c.current_education)
            player.c.activities.append(player.c.college)
        elif (player.c.education == 'college yr 1'):
            message = "You have started your sophomore year of college."
            education = 'college yr 2'
        elif (player.c.education == 'college yr 2'):
            message = "You have started your junior year of college."
            education = 'college yr 3'
        elif (player.c.education == 'college yr 3'):
            message = "You have started your senior year of college."
            education = 'college yr 4'
        player.c.occupation = 'student'
        player.c.education = education
    if (player.c.occupation == "student"  and player.c.education == 'college yr 4' and player.date == '06-01'): # end school year
        check = True
        message = "You have graduated college! Congratulations, it's time to start your career."
        # need to expand this to 4, 6, 8 year colleges
        player.c.occupation = 'work'
        from functions import randomJob
        player.c = randomJob(player,player.c)

    result = messageFunction(fname,message,player,check)
    if (result):
        player.updateClient = True
    return result


def collegeParty(player, type='message', message=False, response=False):
    fname = 'collegeParty'
   
    check = player.weekend and player.c.education == 'college yr 1' and random.random() < .1
    if (check and type != 'answer'):
        message = "Hey! There's a party tonight, wanna go?"
        answerOptions = [answerOption("I'll be there!"),answerOption('No thanks, I should study.')]
        return questionFunction(fname,message,player,True,answerOptions)
    elif (type == 'answer'):
        player.askedQuestions.add(response['data'])
        if (response['option'] == "I'll be there!"):
            player.c.happiness += 5
            player.c.social += 5
        if (response['option'] == 'No thanks, I should study.'):
            player.c.social -= 5


def collegeGreekLife(player, type='message', message=False, response=False):
    fname = 'collegeGreekLife'

    check = player.weekend and player.c.education == 'college yr 1' and random.random() < .1
    if (check and type != 'answer'):
        message = "Would you like to join a fraternity/sorority?"
        answerOptions = [answerOption("Yes!"),answerOption('No thanks, I should study.')]
        return questionFunction(fname,message,player,True,answerOptions)
    elif (type == 'answer'):
        if (response['option'] == "Yes!"):
            player.c.happiness += 5
            player.c.social += 15
            player.c.greekLife = True
        if (response['option'] == 'No thanks, I should study.'):
            player.c.social -= 5


def collegeMissHome(player, type='message'):
    fname = 'collegeMissHome'
    check = player.c.education == 'college yr 1' and player.c.social < 50 and random.random() < .01
    if (check):
        message = 'You miss home, and your family misses you. You should call them.'
        player.events.add(fname)
        return messageFunction(fname,message,player,check)


def adultMissFriends(player, type='message'):
    fname = 'adultMissFriends'
    check = player.c.occupation == 'work' and random.random() < .01
    from functions import find_where_test
    friends = list(find_where_test(player.r,{'affinity__gt':50}))


def collegeMinor(player, type='message', message=False, response=False):
    fname = 'collegeMinor'
    check = player.c.education == 'college yr 1' and random.random() < .1 and not getattr(player.c,'minor',False)
    if (check and type != 'answer'):
        message = "Would you like to choose a minor?"
        #create list of optional minorsx
        answerOptions = ['Art','Biology','Business','Chemistry','Computer Science','Economics','English','History','Mathematics','Music','Philosophy','Physics','Political Science','Psychology','Sociology','Theater']
        return questionFunction(fname,message,player,True,answerOptions)
    elif (type == 'answer'):
        player.c.minor = response['option']
        player.c.energy -= 5
        player.updateClient = True


def driversLessons(player, type='message'):
    from functions import scheduler
    fname = 'driversLessons'
    check = player.c.ageYears >= 15 and player.c.ageYears < 22 and fname not in player.events and 1 >= random.random()*100
    message = "Your parents have signed you up for drivers lessons!"
    if (check):
        player.c.schedules.append(scheduler(player.c,"Drivers Education",["daily","weekday","afterSchool"],location="school"+player.c.id,duration=random.randint(15,20)))
    return messageFunction(fname,message,player,check)


def driversTest(player, type='message', message=False, response=False, dilemma=False):
    fname = 'driversTest'
    from functions import scheduleComplete,ordinal_suffix
    check = fname not in player.askedQuestions and not player.c.canDrive and scheduleComplete(player.c,'Drivers Education') and random.random() < .1
    answerOptions = ["Nervous","Confident"]
    if (type != "answer" and check):
        # Track attempt number using a counter attribute
        if not hasattr(player.c, 'driversTestAttempts'):
            player.c.driversTestAttempts = 0
        player.c.driversTestAttempts += 1
        num = player.c.driversTestAttempts
        message = "Today is your " + ordinal_suffix(num) + " attempt at the driver's test! How are you feeling?"
        return questionFunction(fname,message,player,check,answerOptions)
    if (type == 'answer'):
        # Calculate pass rate: 50% base + 10% per previous attempt (maxes at 90%)
        if not hasattr(player.c, 'driversTestAttempts'):
            player.c.driversTestAttempts = 1
        pass_rate = min(0.9, 0.5 + ((player.c.driversTestAttempts - 1) * 0.1))

        if (random.random() < pass_rate):
            message = "You passed your drivers test!"
            player.c.canDrive = True
            # Only add to askedQuestions when passing to prevent retaking after success
            player.askedQuestions.add(fname)
        else:
            message = "You failed your drivers test!"
            # Don't add to askedQuestions - allow retry
        player.messageQueue.append(message)


def positiveInteraction(player, type='message', message=False, response=False):
    fname = 'positiveInteraction' 
    from functions import find_where_test
    from functions import randArray
    check = len(list(find_where_test(player.r,{'affinity__gt':50}))) > 0
    if (check and type != 'answer' and 1 >= random.random()*1000):
        print('positive interaction')
        p = randArray(list(find_where_test(player.r,{'affinity__gt':1})))
        message = p.firstname + ' is starting to really like you and wants to hang out!'
        return questionFunction(fname,message,player,True)
    elif (type == 'answer'):
        player.controller = "active"


def lowEnergyEvents(player, type='message', message=False, response=False):
    fname = 'lowEnergyEvents'
    if (player.c.energy < 20 and type != 'answer' and player.c.energy >= random.random()*1000):
        messageOptions = {
            "rudeness": "You notice a sharpness creeping into your tone. Fatigue is making you irritable and you're pushing people away.",
            "overeating": "Your tiredness is making you reach for comfort foods. You're overeating and it's not making you feel any better.",
            "isolation": "You're withdrawing from friends and family, opting to be alone. Isolation seems easier when you're this worn out.",
        }
        if (player.c.occupation == 'work'):
            messageOptions["skip_work"] = "You wake up feeling exhausted and decide to skip work today."
        if (player.c.occupation == 'student'):
            messageOptions["skip_school"] = "You wake up feeling exhausted and decide to skip school today."
        if (player.c.ageYears > 21):
            messageOptions["alcohol"] = "Exhaustion sets in and you find yourself reaching for a drink more often than usual."

        coping_mechanism = random.choice(list(messageOptions.keys()))
        message = messageOptions[coping_mechanism]
        answerDict = {
            "rudeness": "I've run out of patience.",
            "overeating": "I just need some comfort food.",
            "isolation": "I just need some alone time.",
            "skip_work": "I need a personal day.",
            "skip_school": "I can't face school today.",
            "alcohol": "Just one more drink to take the edge off.",
        }
        answerOptions = [answerOption(answerDict[coping_mechanism],coping_mechanism)]
            
        return questionFunction(fname,message,player,True,answerOptions)


def extendedFamily(player, type='message', message=False, response=False):
    fname = 'extendedFamily'
    if (type != 'answer'):
        found = []
        for r in player.r:
            if (r.familyLevel == 2):
                if (r.affinity < -50):
                    found.append(r)
        if (len(found) > 0 and 1 >= random.random()*5):
            c = random.choice(found)
            message = c.firstname + " is upset you've been ignoring them, you should have a chat with them!"
            answerOptions = [answerOption("I'll set some time aside to talk to them",c.id),answerOption("I'm ignoring them for a reason!",c.id)]
            return questionFunction(fname,message,player,True,answerOptions)
    elif (type == 'answer' and response):
        from functions import get_person
        p = get_person(player,response['data'])
        if (response['option'] == "I'll set some time aside to talk to them"):
            p.affinity += 20
            player.c.energy -= 20
        else:
            p.affinity -= 10


def murderAttempt(player, type='message', message=False, response=False):
    fname = 'murderAttempt' 
    from functions import find
    from functions import randArray
    check = len(list(find(player.r,{'affinity':-100}))) > 0
    if (check and 1 >= random.random()*100000 and type != 'answer'):
        p = randArray(list(find(player.r,{'affinity':-100})))
        message = p['firstname'] + ' hates you so much they break into your house and stab you in your sleep.'
        return questionFunction(fname,message,player,True)


def funeral(player, type='message', message=False, response=False):
    for person in player.r: 
        check = False
        fname = 'funeral---'+person.firstname+person.lastname
        if type != 'answer' and person.status != 'alive' and fname not in player.events:
            check = True
            message = person.firstname+' '+person.lastname+' has passed away, would you like to attend their funeral?'
            return questionFunction(fname,message,player,check)
        elif (type == 'answer' and message == person.firstname+person.lastname):
            player.events.add(fname)
            if (response['option'] == "Yes"):
                player.c.happiness -= 15
                player.c.social -= 15
                from functions import scheduler
                player.c.schedules.append(scheduler(player.c,"Funeral",["once","afternoon","weekend"],location="cemetery"+player.c.id,duration=1))
            elif(response['option'] == "No"):
                player.messageQueue.append("You did not attend the funeral.")


__all__ = [
    'school',
    'graduate5th',
    'graduate8th',
    'graduate12th',
    'college',
    'collegeParty',
    'collegeGreekLife',
    'collegeMissHome',
    'adultMissFriends',
    'collegeMinor',
    'driversLessons',
    'driversTest',
    'positiveInteraction',
    'lowEnergyEvents',
    'extendedFamily',
    'murderAttempt',
    'funeral',
]
