// JavaScript Document

const scaling = "fit"; 
const width = 1024;
const height = 768;
const color = yellow;
const outerColor = white;
const assets = ["cup.png", "backing.mp3", "end.mp3", "tada.mp3", "sort.mp3", "shake.mp3", "click.mp3", {font:"Reuben", src:"Reuben.otf"}, "b0.mp3", "b1.mp3", "b2.mp3", "b3.mp3", "b4.mp3", "b5.mp3", "b6.mp3", "b7.mp3", "b8.mp3", "b9.mp3"];
const path = "https://d309knd7es5f10.cloudfront.net/shake/";

const frame = new Frame(scaling, width, height, color, outerColor, assets, path, new Waiter({backgroundColor:purple}));
frame.on("ready", ()=>{
    zog("ready from ZIM Frame"); 

    const stage = frame.stage;
    let stageW = frame.width;
    let stageH = frame.height;

    
    // ~~~~~~~~~~~~  INTRO
    STYLE = {font:"Reuben"}
    const intro = new Pane(stageW+50, 200, "Ρίξε μάρκες", purple, white).show(); 

    intro.on("close", makeApp);
    
    function makeApp() {
        
        stage.removeAllChildren();        
        
        // ~~~~~~~~~~~~  TITLE
        const title = new LabelLetters({
            label:new Label({
                text:" ",
                size:30,
                color:purple
            })
        })
            .pos(0, 150, CENTER) 
            .animate({
                from:true, 
                time:.4,
                ease:"backOut",
                props:{y:-200},
                sequence:.05 
            });
        
        STYLE = {};  
        
        const instuctions1 = new Label({
            text:"Ρίξε 3 έως 10 μάρκες,  \n στη συνέχεια κάνε κλικ το κύπελλο!",
            align:RIGHT,
            lineHeight:45
        })
            .sca(.9)
            .alp(.8)
            .loc(800, 143)
            .animate({
                from:true,
                props:{alpha:0},
                wait:2
            })
        
        
        // ~~~~~~~~~~~~  MUSIC AND SOUND DATA
        let rememberedMusic = true;
        if (localStorage && localStorage.rememberedMusic) {
            rememberedMusic = JSON.parse(localStorage.rememberedMusic);
        }  
        let rememberedSound = true;
        if (localStorage && localStorage.rememberedSound) {
            rememberedSound = JSON.parse(localStorage.rememberedSound);
        }        
        const backingSound = asset("backing.mp3").play(0, true);
        if (rememberedMusic && rememberedSound) {
            animate(backingSound, {volume:.1}, 2);
        } 
        if (rememberedSound) {
            timeout(1, ()=>{ 
                asset("shake.mp3").play(.5);
            });
        }
        
        
        // ~~~~~~~~~~~~  CUP
        
        const spacing = 20; 
        const answers = [0,0,0]; 
        const cupPic = asset("cup.png").clone().sca(.5);
        const cup = new Container(cupPic.width, cupPic.height)       
            .reg(cupPic.width, cupPic.height)        
            .pos(100, 100, LEFT, CENTER);
        cup.startX = cup.x;
        cup.startY = cup.y;
            
        cupPic
            .reg(cupPic.width, cupPic.height)
            .center(cup);            
        cupPic.on("mousedown", shake);
            
        const counter = new Circle(40, blue, dark, 2)
            .loc(cup.width/2, -100, cup)           
            .cur()
            .animate({
                wait:1.5,
                from:true,
                time:1.5,
                props:{x:-200},
                ease:"elasticOut"
            })
        counter.on("mousedown", drop);
        const counters = new Container().addTo(cup);
        let dropTimer; 
        
        function drop() {    
            if (dropTimer) dropTimer.clear();  
            dropTimer = timeout(1, ()=>{dropTimer = null;}); 
            let num = counters.numChildren;
            if (sound.toggled) asset("b"+num+".mp3").play(.8);
            timeout(.3, bounceSound);      
            let colors = series(red, blue); 
            let copy = counter.clone()
                .addTo(counters)
                .rot(rand(360))
                .animate({
                    props:{scaleX:0},
                    time:rand(.1,.2), 
                    loop:true,
                    rewind:true,
                    rewindCall:()=>{ 
                        copy.color = colors();
                    }                
                })
                .animate({
                    props:{x:String(rand(-50,50))}, 
                    wait:.6, // wait until it bounces
                    time:.4
                })
                .animate({
                    props:{y:"400"},
                    ease:"bounceOut",
                    call:() => { 
                        copy.stopAnimate();
                        copy.sca(1);
                        copy.color = rand()>.5?red:blue;                                     
                    }
                });  
                if (counters.numChildren >= 3) cupPic.cur();  
                if (counters.numChildren >= 10) counter.removeFrom(); 
        }
        
        function bounceSound() {
            if (!sound.toggled) return; 
            asset("click.mp3").play(.8);
            timeout(.2, () => {
                asset("click.mp3").play(.5);
                timeout(.2, () => {
                    asset("click.mp3").play(.2);
                });
            });
        }      
        
        // ~~~~~~~~~~~~  MUSIC AND SOUND CONTROLS   
        
        const music = new CheckBox({label:"Μουσική", color:grey, startToggled:rememberedMusic})
            .sca(.6)
            .pos(40,40,LEFT,BOTTOM)
            .alp(0)
            .animate({
                props:{alpha:.8},
                wait:1.5
            }).change(() => {
                if (localStorage) localStorage.rememberedMusic = JSON.stringify(music.toggled);               
                if (sound.toggled) animate(backingSound, {volume:music.toggled?.1:0})
            });  
        
        const sound = new Toggle({label:"Ήχος", backgroundColor:silver, color:grey, startToggled:rememberedSound})
            .sca(.8)
            .pos(0,40,CENTER,BOTTOM)
            .alp(0)
            .animate({
                props:{alpha:.8},
                wait:2
            }).change(() => {
                if (localStorage) localStorage.rememberedSound = JSON.stringify(sound.toggled);               
                if (music.toggled) animate(backingSound, {volume:sound.toggled?.1:0})
            });
            
        
        // ~~~~~~~~~~~~  SHAKE
        
        function shake() {
            if (counters.numChildren < 3) return;
            if (dropTimer) return; 
            if (sound.toggled) asset("shake.mp3").play(.8);
            timeout(1, bounceSound);
            timeout(1.1, bounceSound);
            instuctions1.animate({alpha:0},.5); 
            cup.noMouse(); // do not let a second click
            counter.removeFrom();
            cup.wiggle("x", cup.x, 20, 40, .05, .1, .7);
            cup.wiggle("rotation", 0, 2, 5, .05, .1, .7);
            counters.loop(counter=>{
                if (counter.color==blue) answers[0]++;
                if (counter.color==red) answers[1]++;
                answers[2]++;
            });
            timeout(.75, spill); 
        }
        
        // ~~~~~~~~~~~~  SPILL
        
        function spill() { 
            cup.loc(cup.startX, cup.startY)       
                .animate({
                    props:{x:cup.startX-380, rotation:90},
                    time:1,
                    ease:"bounceOut"
                });

            cupPic.animate({
                props:{rotation:-10},
                time:1
            });

            counters.loop((counter,i)=>{
                counter.animate({
                    props:{
                        y:-460+Math.floor(i/2)*(counter.width+spacing),
                        x:i%2==0?100+counter.width+spacing:100
                    },
                    wait:i*.05 
                });            
            });        
            timeout(2, details); 
        }
        
        
        // ~~~~~~~~~~~~  NUMBERS
        
        function details() {
            const instructions2 = new Label("Βάλε τους αριθμούς")
                .sca(.9)
                .alp(0)
                .loc(450, 184)
                .animate({alpha:.8}, .7)
                //.place();
            const test = new Container()
                .sca(.8)
                .loc(447, 285)
                .animate({
                    props:{x:stageW+200},
                    ease:"backOut",
                    time:.7,
                    wait:.3,
                    from:true
                })
                // .place();
                
            if (sound.toggled) {
                asset("tada.mp3").play(.8);
                timeout(.8, () => {
                    asset("tada.mp3").play(.8);
                });
            }
            

            STYLE = {
                type:{
                    Stepper:{
                        color:series(blue,red,tin), 
                        borderColor:series(blue,red,tin),
                        borderWidth:4,
                        delayPick:true,
                        shadowColor:-1
                    }
                }
            }
            // obj, cols, rows, spacingH, spacingV
            const steppers = new Tile(new Stepper(), 3, 1, 50)
                .sca(.5)
                .addTo(test)
                .change(()=>{
                    let answer = steppers.loop((stepper, i)=>{
                        if (stepper.currentValue != answers[i]) return false;
                    });
                    if (answer) correct();
                });
            STYLE = {};  
            const instructions3 = new Label("Μπλε           κόκκινοι           σύνολο")
                .sca(.8)
                .alp(.8)
                .center(test)
                .mov(5,60)
                
               
            
            
            // ~~~~~~~~~~~~  SORT
            
            new Button({
                backgroundColor:green,
                rollBackgroundColor:tin,
                label:"Ταξινόμηση"
            })
                .sca(.6)
                .pos(275,50,RIGHT,BOTTOM)
                .animate({
                    wait:1,
                    props:{y:stageH+100},
                    ease:"backOut",
                    time:.7,
                    from:true
                })
                .tap(e => {
                    const sorted = [];
                    loop(answers[1], ()=>{sorted.push(red)});
                    loop(answers[0], ()=>{sorted.push(blue)});
                    counters.loop((counter, i) => {
                        if (sorted[i]!=counter.color) counter.animate({color:sorted[i]});
                    });
                    if (sound.toggled) asset("sort.mp3").play(.8);
                    e.target.animate({ 
                        wait:1,
                        props:{y:stageH+100},
                        ease:"backIn",
                        time:.7
                    });
                }); 
                
                
                // ~~~~~~~~~~~~  CORRECT
                
                const emitter = new Emitter({
                    obj:new Circle(50, [red, blue, green], dark, 2),
                    force:{min:7, max:14},
                    num:2,
                    gravity:0,
                    startPaused:true
                });
                const pane = new Pane(600,250,"Μπράβο!", purple, white);
                pane.on("close", () => {
                    steppers.mouse(); 
                });
                new Button({
                    backgroundColor:yellow,
                    rollBackgroundColor:green,
                    label:"Παίξε πάλι!",
                    color:dark,
                    rollColor:dark,
                    shadowColor:-1                 
                }).center(pane).mov(0,50).tap(() => {
                    makeApp();
                });
                pane.label.mov(0,-50);
                                
                function correct() { 
                    if (sound.toggled) asset("end.mp3").play(.8);
                    steppers.noMouse(); 
                    emitter.center().spurt(60);
                    timeout(.5, () => {                          
                        pane.show();
                    });
                } 
                
            stage.update();
        }
        
<!--        frame.madeWith().pos(135,140,RIGHT,BOTTOM); -->
        
    }      
    
}); 
