from cgi import test
from cmath import pi
from tkinter import CENTER
from PIL import Image, ImageDraw, ImageFont, ImagePath
import textwrap
import botOptions
import random
import math
import time
  
watermarkFont = ImageFont.truetype('Roboto-Bold.ttf',120)
textFont = ImageFont.truetype('Roboto-Bold.ttf',23)
 
def generate_bingo(playerName,seed):
    random.seed(seed)
    background = Image.open('background.png')
    midground = Image.open('midground.png')
    draw = ImageDraw.Draw(background)
    #Draw Watermark
    draw.text((500,1000),playerName,font=watermarkFont,fill=(100,0,0),anchor='mb')
    background.paste(midground,(0,0),midground)
    selectedTasks = random.sample(botOptions.alternatives,25)
    for x in range(0,5):
        for y in range(0,5):

            wrapText = textwrap.fill(text=selectedTasks.pop(),width=13)
            draw.multiline_text((137+(180*x),267+(180*y)),wrapText,font=textFont,fill=(0,0,0,),anchor='mm',align=CENTER)
    return background

def generate_gif_test(displayname,tier):
    images = []
    frameCount = 80
    startAngle = random.random()*720
    im = Image.new("RGBA", (582, 582), (44, 47, 51,255))
    wheelGenResult = drawWheel(tier)
    wheel = wheelGenResult[0]
    endAngle = (startAngle+(10*(frameCount-1)))%360
    #print(endAngle)
    targetAngle = 180-endAngle
    #Calculate winning segment
    if endAngle > 180:
        targetAngle = 360 - endAngle + 180
    #print(wheelGenResult)
    #print(targetAngle)
    for n,seg in enumerate(wheelGenResult[1]):
        if seg[0]+seg[1] > targetAngle:
            reward = getTierAwards(tier)[n][2]
            #print(reward)
            break

    dot = Image.open('dot.png')
   
    for n in range(0,frameCount):
        frame = im.copy()
        draw = ImageDraw.Draw(frame)

        
        rotwheel = wheel.rotate(startAngle+(n*10))
        rotwheel.paste(dot,(0,0),dot)
        frame.paste(rotwheel,(0,0),rotwheel)
        images.append(frame)
    c=im.width/2
    #draw.line((c,c)+(c+250*math.sin((endAngle)/180*pi),c+250*math.cos((endAngle)/180*pi)))
    images[0].save(displayname+'.gif',
               save_all=True,
               append_images=images[1:],
               duration=22,
               loop=1)
    return reward

def getTierAwards(number):
    #imageIcons
    #Tier one
    tier1 = [
        (0,Image.open('resources/1kweps.png'),"1000 Weapons"),
        (0,Image.open('resources/250kgold.png'),"250k Parish Gold"),
        (0,Image.open('resources/250cat.png'),"250 Catapults"),
        (0,Image.open('resources/100kpitch.png'),"100k Pitch"),
        (0,Image.open('resources/fullbanquet.png'),"2700 Banqueting Goods"),
        (10,Image.open('resources/t2.png'),"T2")
    ]
    #Tier two
    tier2 = [
        (0,Image.open('resources/500kgold.png'),"500k Parish Gold"),
        (0,Image.open('resources/500cat.png'),"500 Catapults"),
        (0,Image.open('resources/2kweps.png'),"2000 Weapons"),
        (6,Image.open('resources/t3.png'),"T3")
    ]
    #Tier three
    tier3 = [
        (0,Image.open('resources/1mgold.png'),"1MILLION GOLD"),
        (0,Image.open('resources/1kcat.png'),"1000 Catapults"),
        (0,Image.open('resources/3kweps.png'),"3000 Weapons"),
        (0,Image.open('resources/5crowns.png'),"$5 Crown Gift")
    ]
    if number >= 3:
        return tier3
    elif number == 2:
        return tier2
    else:
        return tier1


def drawWheel(tier):
    awards = getTierAwards(tier)
    im = Image.new("RGBA", (582, 582), (44, 47, 51,0))
    c = im.width/2
    radius = 290
    segments = []

    #generate segment sizes
    fairChance =  100
    specials = 0
    circleCheck = 0
    for a in awards:
        if a[0] > 0:
            fairChance -= a[0]
            specials +=1

    for award in awards:
        #set arclengths
        if award == awards[-1]:
            arc = 360-circleCheck
            circleCheck += arc
            segments.append((arc,award))
            break
        if award[0] == 0:
            arc = int((361*fairChance/100)/(len(awards)-specials))
            circleCheck += arc
            segments.append((arc,award))
        else:
            arc = int(361*award[0]/100)
            circleCheck += arc
            segments.append((arc,award))

    polygons = []
    iconPositions = []
    sectorAreas = []
    sectorStart = 0
    for seg in segments:
        sectorSize = seg[0]
        polygons.append(drawSegmentVector(sectorStart,sectorSize,c,radius))
        sectorAreas.append((sectorStart,sectorSize))
        iconPositions.append(int(sectorStart+(sectorSize/2)))
        sectorStart += seg[0]
    imdraw = ImageDraw.Draw(im)
    #selectedColors = random.sample(circleColors,len(polygons))
    for polys in polygons:
        imdraw.polygon(polys,fill=random.choice(botOptions.circleColors),outline='black')
    #add icons to center of segment
    for index,iconArc in enumerate(iconPositions):
        icon = awards[index][1]
        rotIcon = icon.rotate(iconArc-180)
        imgSize = icon.size
        
        im.paste(rotIcon,(int(c+(radius*0.75)*math.sin((iconArc)/180*pi))-int(imgSize[0]/2),int(c+(radius*0.75)*math.cos((iconArc)/180*pi))-int(imgSize[1]/2)),mask=rotIcon)
    #im.show()
    return((im,sectorAreas))


def drawSegmentVector(arcStart,arcLength,center,radius):
    vectors = []
    vectors.append((center,center)) #Start in center
    for a in range(0,arcLength+1):
        vectors.append((center+radius*math.sin((a+arcStart)/180*pi),center+radius*math.cos((a+arcStart)/180*pi)))
    vectors.append((center,center)) #End in center
    return vectors

#generate_gif_test("test",1)