var stage = null;
var canvas = null;
var stampList = [];
if (typeof (localStorage.data) == "undefined") localStorage.data = "[]";


// 定義基本資料
var stampImgList = [
    {
        id: 1, name: "GBF 2018四周年", image_data: [
            { id: 10, name: "10.png", x: 53, y: 441, input: false },
            { id: 20, name: "20.png", x: 153, y: 441, input: false },
            { id: 30, name: "30.png", x: 253, y: 441, input: false },
            { id: 100, name: "100.png", x: 353, y: 441, input: false }
        ],
        pos_data: [
            { x: 63, y: 213 }
            , { x: 153, y: 213 }
            , { x: 243, y: 213 }
            , { x: 333, y: 213 }
            , { x: 423, y: 213 }
            , { x: 513, y: 213 }
            , { x: 603, y: 213 }
            , { x: 63, y: 303 }
            , { x: 153, y: 303 }
            , { x: 243, y: 303 }
            , { x: 333, y: 303 }
            , { x: 423, y: 303 }
            , { x: 513, y: 303 }
            , { x: 603, y: 303 }
        ]
    },
    {
        id: 2, name: "GBF 2018聖誕節", image_data: [
            { id: "10", name: "10.png", x: 53, y: 420, input: false },
            { id: "20", name: "20.png", x: 153, y: 420, input: false },
            { id: "30", name: "30.png", x: 253, y: 420, input: false },
            { id: "100", name: "100.png", x: 353, y: 420, input: false },
            { id: "atama", name: "atama.png", x: 453, y: 420, input: false },
            { id: "input", name: "input.png", x: 553, y: 420, input: true, text: "" },
        ],
        pos_data: [
            { x: 43, y: 219 }
            , { x: 133, y: 219 }
            , { x: 223, y: 219 }
            , { x: 313, y: 219 }
            , { x: 403, y: 219 }
            , { x: 493, y: 219 }
            , { x: 583, y: 219 }
            , { x: 43, y: 311 }
            , { x: 133, y: 311 }
            , { x: 223, y: 311 }
            , { x: 313, y: 311 }
            , { x: 403, y: 311 }
            , { x: 493, y: 311 }
            , { x: 583, y: 311 }
        ]
    }
];


function init() {
    var curEventId = $("select[name=EventList]").val();
    var curPath = "./" + curEventId + "/"

    canvas = document.querySelector('#gbfCanvas');
    stage = new createjs.Stage("gbfCanvas");
    stage.enableMouseOver();

    // 背景圖片
    var stampCard = new createjs.Bitmap(curPath + "main.png");
    stage.addChild(stampCard);

    // point
    stampList = [];
    var curStampImgList = Enumerable.from(stampImgList).where(function (obj) { return obj.id == curEventId; }).firstOrDefault().image_data;
    for (var i in curStampImgList) {
        var stamp = curStampImgList[i];

        var stampData = new baseData();
        stampData.Id = stamp.id;
        stampData.ImageName = curPath + stamp.name;
        stampData.input = stamp.input;
        stampData.text = stamp.text;
        stampData.ImageX = stamp.x;
        stampData.ImageY = stamp.y;
        stampData.setObj();
        stage.addChild(stampData.Obj);
        stampList.push(stampData);
    }
    // space
    curPos = Enumerable.from(stampImgList).where(function (obj) { return obj.id == curEventId; }).firstOrDefault().pos_data;

    // 代入上次存檔值
    var tmpData = JSON.parse(localStorage.data);
    var tmpStampData = Enumerable.from(tmpData).where(function (obj) { return obj.id == curEventId; }).firstOrDefault();
    if (tmpStampData == null) tmpStampData = { id: curEventId, data: [] };
    var curStampData = tmpStampData.data;
    for (var index in curStampData) {
        var item = curStampData[index];
        stampData = new baseData();
        stampData.Id = item.Id;
        for (var i in stampList) {
            var tmpStamp = stampList[i];
            if (tmpStamp.Id == item.Id) stampData.ImageName = tmpStamp.ImageName;
        }
        stampData.ImageX = item.ImageX;
        stampData.ImageY = item.ImageY;
        stampData.input = item.input;
        stampData.text = item.text;
        stampData.IsRestore = true;
        stampData.setObj();
        if (stampData.input) {
            var t = new createjs.Text(item.text, "18px sans-serif", "#000000");
            t.x = stampData.ImageX + 8;
            t.y = stampData.ImageY + 8;
            stampData.Obj.textObj = t;
            stage.addChild(stampData.Obj);
            stage.addChild(t);
        }else{
            stage.addChild(stampData.Obj);
        }
    }
    // 測點用
    function checkPoint(event) {
        console.info(stage.mouseX);
        console.info(stage.mouseY);
    }
    // stage.addEventListener("mousedown", checkPoint);

    // tick イベントを監視します
    createjs.Ticker.setFPS(60);
    createjs.Ticker.on("tick", function () {
        // Stageの描画を更新します
        stage.update();
    });
}

function baseData() {
    var _Func = this;
    _Func.Id = "";
    _Func.IsRestore = false;
    _Func.input = false;
    _Func.text = "";
    _Func.Obj = null;
    _Func.ImageName = "";
    _Func.ImageX = 0;
    _Func.ImageY = 0;

    _Func.setObj = function () {
        _Func.Obj = new createjs.Bitmap(_Func.ImageName);
        _Func.Obj.customId = _Func.Id;
        _Func.Obj.input = _Func.input;
        _Func.Obj.text = _Func.text;
        _Func.Obj.x = _Func.ImageX;
        _Func.Obj.y = _Func.ImageY;

        if (!_Func.IsRestore) {
            _Func.Obj.addEventListener("mousedown", handleDown);
            _Func.Obj.addEventListener("pressmove", handleMove);
            _Func.Obj.addEventListener("pressup", handleUp);
        } else {
            _Func.Obj.addEventListener("click", function () { console.info(_Func.Obj); });
            _Func.Obj.addEventListener("dblclick", deleteSelf);
        }
        _Func.Obj.cursor = 'pointer';

        _Func.Obj.addEventListener('mouseover', function (e) {
            canvas.className = 'mouseon';
        });


    }
    function deleteSelf(event) {
        var curEventId = $("select[name=EventList]").val();

        var tmpData = JSON.parse(localStorage.data);
        var tmpStampData = Enumerable.from(tmpData).where(function (obj) { return obj.id == curEventId; }).firstOrDefault();
        if (tmpStampData == null) {
            tmpData.push({ id: curEventId, data: [] });
            tmpStampData = Enumerable.from(tmpData).where(function (obj) { return obj.id == curEventId; }).firstOrDefault();
        }
        var curStampData = tmpStampData.data;

        var curData = [];
        for (var index in curStampData) {
            var item = curStampData[index];
            var thisObj = Enumerable.from(stage.children).where(function (obj) { return obj.id === event.target.id }).firstOrDefault();

            if (item.Id != thisObj.customId
                || item.ImageX != event.target.x
                || item.ImageY != event.target.y
            ) {
                curData.push(item);
            } else {
                console.info(thisObj);
            }
        }
        tmpStampData.data = curData;
        localStorage.data = JSON.stringify(tmpData);
        if (event.target.input) stage.removeChild(event.target.textObj);
        stage.removeChild(event.target);
    }
    function handleDown(event) {
        // ドラッグを開始した座標を覚えておく
        dragPointX = stage.mouseX - event.target.x;
        dragPointY = stage.mouseY - event.target.y;
        // ボールを半透明にする
        event.target.alpha = 0.5;
    }
    // ボールを押した状態で動かしたときの処理です

    function handleMove(event) {
        // ボールはマウス座標に追随する
        // ただしドラッグ開始地点との補正をいれておく
        event.target.x = stage.mouseX - dragPointX;
        event.target.y = stage.mouseY - dragPointY;
    }
    // ボールからマウスを離したときの処理です

    function handleUp(event) {
        var curEventId = $("select[name=EventList]").val();

        // ボールを元の透明度に戻す
        event.target.alpha = 1.0;

        for (var index in curPos) {
            var item = curPos[index];
            if (event.target.x >= (item.x - 30)
                && event.target.x <= (item.x + 30)
                && event.target.y >= (item.y - 30)
                && event.target.y <= (item.y + 30)
            ) {
                var cloneObj = event.target.clone();
                cloneObj.customId = event.target.customId;
                cloneObj.input = event.target.input;
                // cloneObj.x = item.x + 8;
                // cloneObj.y = item.y + 8;
                var tmpData = JSON.parse(localStorage.data);
                var tmpStampData = Enumerable.from(tmpData).where(function (obj) { return obj.id == curEventId; }).firstOrDefault();
                if (tmpStampData == null) {
                    tmpData.push({ id: curEventId, data: [] });
                    tmpStampData = Enumerable.from(tmpData).where(function (obj) { return obj.id == curEventId; }).firstOrDefault();
                }
                var curStampData = tmpStampData.data;

                var tmpBase = new baseData();
                tmpBase.Id = event.target.customId;
                tmpBase.ImageX = event.target.x;
                tmpBase.ImageY = event.target.y;
                tmpBase.input = event.target.input;
                if (tmpBase.input) {
                    tmpBase.text = prompt("請輸入欲顯示之文字", "");
                    var t = new createjs.Text(tmpBase.text, "18px sans-serif", "#000000");
                    t.x = tmpBase.ImageX + 8;
                    t.y = tmpBase.ImageY + 8;
                    cloneObj.textObj = t;
                    stage.addChild(cloneObj);
                    stage.addChild(t);
                }else{
                    stage.addChild(cloneObj);
                }
                tmpBase.IsRestore = true;
                cloneObj.addEventListener("dblclick", deleteSelf);


                curStampData.push(tmpBase);
                localStorage.data = JSON.stringify(tmpData);
            }
        }

        for (var index in stampList) {
            var item = stampList[index];
            if (item.Id == event.target.customId) {
                event.target.x = item.ImageX;
                event.target.y = item.ImageY;
            }
        }
    }
}

function stampChecker() {
    var _Func = this;
    _Func.x = 0;
    _Func.y = 0;
}

$(function () {
    window.addEventListener("load", init);

    $("select[name=EventList]").on("change", function () {
        stage.removeAllChildren();
        stage.update();
        init();
    });
});


