import LabelType from "./LabelType";
import StartScene from "./StartScene";
const groups = [
    LabelType.IceCream,
    LabelType.Donut,
    LabelType.Egg,
    LabelType.Candy2, LabelType.Gift2,];
const groupName: any = {};
groupName[LabelType.Candy2] = '糖果';
groupName[LabelType.Donut] = '甜甜圈';
groupName[LabelType.Egg] = '彩蛋';
groupName[LabelType.Gift2] = '礼盒';
groupName[LabelType.IceCream] = '冰淇淋';
let currentLv;

const datastr = localStorage.getItem('data');
let data = datastr ? JSON.parse(datastr) : {};
const currentLvstr = localStorage.getItem('currentLv');
currentLv = currentLvstr ? currentLvstr : groups[0];

let that: StartScene;
const MAX = 3;

export const initLevel = ($that: StartScene) => {
    that = $that;
    initProgressBar();
    updateLevelView(false);
}

export const resetLevel = () => {
    resetData();
    updateLevelView(false)
}

export const resetData = () => {
    if (!isAllLevelPass()) return;
    data = {};
    currentLv = groups[0];
    localStorage.setItem('data', '{}');
    localStorage.setItem('currentLv', groups[0])
}

export const isLevelPass = () => {
    return getProgress(currentLv) == MAX
}

export const isAllLevelPass = () => {
    return getProgress(groups[groups.length - 1]) == MAX
}

export const addItem = async (type) => {
    if (currentLv != type) return;
    if (data[type] == undefined)
        data[type] = 0;
    data[type]++;
    let add = true;
    if (data[type] > MAX) {
        data[type] = MAX;
        add = false;
    }
    localStorage.setItem('data', JSON.stringify(data));
    await updateLevelView(add);
}

export const clearLevel = () => {
    data[currentLv] = 0;
    localStorage.setItem('data', JSON.stringify(data));
    // updateLevelView(false);
}

export const nextLevel = () => {
    const i = groups.indexOf(currentLv);
    currentLv = groups[i + 1];
    localStorage.setItem('currentLv', currentLv);
    updateLevelView(false);
}

export const getCurrentLv = () => { return currentLv }

export const getCurrentName = () => { return groupName[currentLv] }

export const updateLevelView = async (add) => {
    hideAllGroup();
    that['awardDisabled'].visible = that['award'].visible = !isAllLevelPass();
    that[currentLv].visible = true;
    that['condition'].text = `本轮需获3个${groupName[currentLv]}`

    if (!that['condition'].filters || that['condition'].filters.length < 1) {
        var color: number = 0x1ec9bf;        /// 光晕的颜色，十六进制，不包含透明度
        var alpha: number = 1;             /// 光晕的颜色透明度，是对 color 参数的透明度设定。有效值为 0.0 到 1.0。例如，0.8 设置透明度值为 80%。
        var blurX: number = 5;              /// 水平模糊量。有效值为 0 到 255.0（浮点）
        var blurY: number = 5;              /// 垂直模糊量。有效值为 0 到 255.0（浮点）
        var strength: number = 2;            /// 压印的强度，值越大，压印的颜色越深，而且发光与背景之间的对比度也越强。有效值为 0 到 255。暂未实现
        var quality: number = egret.BitmapFilterQuality.HIGH;        /// 应用滤镜的次数，建议用 BitmapFilterQuality 类的常量来体现
        var inner: boolean = false;            /// 指定发光是否为内侧发光，暂未实现
        var knockout: boolean = false;            /// 指定对象是否具有挖空效果，暂未实现
        var glowFilter: egret.GlowFilter = new egret.GlowFilter(color, alpha, blurX, blurY,
            strength, quality, inner, knockout);

        that['condition'].filters = [glowFilter];
    }
    await setProgress(currentLv, getProgress(currentLv), add);
    await updateProgressBar();
}

const getProgress = (type) => {
    if (data[type] == undefined)
        return 0
    return data[type];
}

const setProgress = (type, progress, add) => {
    return new Promise((r) => {
        hideAllItem(type);
        let target;
        if (progress == 0) {
            that[`${type}_0_1`].visible = true;//0是背景
            that[`${type}_0_2`].visible = true;
            that[`${type}_0_3`].visible = true;
            that[`${type}_1_1`].visible = false;
            that[`${type}_1_2`].visible = false;
            that[`${type}_1_3`].visible = false;
        }
        if (progress == 1) {
            that[`${type}_0_1`].visible = false;//0是背景
            that[`${type}_0_2`].visible = true;
            that[`${type}_0_3`].visible = true;
            that[`${type}_1_1`].visible = true;
            that[`${type}_1_2`].visible = false;
            that[`${type}_1_3`].visible = false;
            if (add) target = that[`${type}_1_1`]
        }
        if (progress == 2) {
            that[`${type}_0_1`].visible = false;//0是背景
            that[`${type}_0_2`].visible = false;
            that[`${type}_0_3`].visible = true;
            that[`${type}_1_1`].visible = true;
            that[`${type}_1_2`].visible = true;
            that[`${type}_1_3`].visible = false;
            if (add) target = that[`${type}_1_2`]
        }
        if (progress == 3) {
            that[`${type}_0_1`].visible = false;//0是背景
            that[`${type}_0_2`].visible = false;
            that[`${type}_0_3`].visible = false;
            that[`${type}_1_1`].visible = true;
            that[`${type}_1_2`].visible = true;
            that[`${type}_1_3`].visible = true;
            if (add) target = that[`${type}_1_3`]
        }
        if (target) {
            target.scaleX = target.scaleY = 0;
            egret.Tween.get(target).set({ scaleX: 0, scaleY: 0 }).to({ scaleX: 1, scaleY: 1 }, 500, egret.Ease.getElasticOut(1, 0.3)).call(() => r())
        } else r();
    });

}

const hideAllGroup = () => {
    groups.forEach(group => {
        that[group].visible = false;
    })
}

const hideAllItem = (type) => {
    const names = getItemNames(type);
    names.forEach(name => that[name].visible = false);
}

const getItemNames = (type) => {
    const list = [];
    for (let i = 1; i <= 3; i++) {
        list.push(`_0_${i}`);
    }
    for (let i = 1; i <= 3; i++) {
        list.push(`_1_${i}`);
    }
    return list.map(item => `${type}${item}`)
}

const initProgressBar = () => {
    const progressfg = that['progressfg'];
    const rect = new egret.Rectangle(0, 0, 558, 60);
    rect.width = 0;
    progressfg.mask = rect;
    progressfg['rect'] = rect;

}

const updateProgressBar = () => {
    return new Promise((r) => {
        const progressfg = that['progressfg'];
        let counter = 0;
        for (const group of groups) {
            counter += getProgress(group);
        }
        const targetWidth = 558 * (counter / groups.length / 3);
        egret.Tween.removeTweens(progressfg.mask);
        egret.Tween.get(progressfg.mask).to({ width: targetWidth }, 200).call(r);
    })

}