/* global jQuery */
/*eslint-disable*/

'use strict';

// API Url
var apiUrl = 'http://localhost:8089/PPSignSDK/';

// initialize device web api
var initUrl = apiUrl + 'InitialDevice?id=2&width=580&height=380';
var initL500Url = apiUrl + 'InitialDevice?id=5&width=580&height=380';
var initL501GUrl = apiUrl + 'InitialDevice?id=7&width=580&height=380';
var initLC700Url = apiUrl + 'InitialDevice?id=3&width=580&height=380';
var initE640Url = apiUrl + 'InitialDevice?id=4&width=580&height=380';

// uninitialize device web api
var uninitUrl = apiUrl + 'UninitialDevice?id=2';
var uninitL500Url = apiUrl + 'UninitialDevice?id=5';
var uninitL501GUrl = apiUrl + 'UninitialDevice?id=7';
var uninitLC700Url = apiUrl + 'UninitialDevice?id=3';
var uninitE640Url = apiUrl + 'UninitialDevice?id=4';

// get ink web api
var getInkUrl = apiUrl + 'GetInks';
// clear ink api
var clrInkUrl = apiUrl + 'Clear';
// GetDeviceConfirmOrCancelKeyStatus
var confirmStatusUrl = apiUrl + 'GetDeviceConfirmOrCancelKeyStatus';
// get save drawing api
var savedrawUrl = apiUrl + 'SaveDrawingImage?';

var canvas;
var context;

var isPolling = false;
var LastSignatureBase64Data;
var isL500Connected = false;
var isL501GConnected = false;
var isLC700Connected = false;
var isE640Connected = false;

// initialize device
function initDevice() {
    $.ajax({
        url: initUrl,
        type: 'GET',
        cache: false
    }).done(function (response) {
        if (response === true) {
            isPolling = true;

            getInk();
            getStatus();

            $('.init').removeAttr('disabled');
            $('#initBtn').attr('disabled', 'disabled');
        } else {
            initL500Device();
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
//        alert('Connection fail(' + jqXHR.status + ')!');
        alert('未检测到[蒙恬电子签名板],请更换USB接口或关闭杀毒饮件试试，若仍有问题请联络蒙恬客服 !');
    });
}

function initL500Device() {
    $.ajax({
        url: initL500Url,
        type: 'GET',
        cache: false
    }).done(function (response) {
        if (response === true) {
            isPolling = true;
            isL500Connected = true;

            getInk();
            getStatus();

            $('.init').removeAttr('disabled');
            $('#initBtn').attr('disabled', 'disabled');
        } else {
            initL501GDevice();
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
//        alert('Connection fail(' + jqXHR.status + ')!');
        alert('未检测到[蒙恬电子签名板],请更换USB接口或关闭杀毒饮件试试，若仍有问题请联络蒙恬客服 !');
    });
}

function initL501GDevice() {
    $.ajax({
        url: initL501GUrl,
        type: 'GET',
        cache: false
    }).done(function (response) {
        if (response === true) {
            isPolling = true;
            isL501GConnected = true;

            getInk();
            getStatus();

            $('.init').removeAttr('disabled');
            $('#initBtn').attr('disabled', 'disabled');
        } else {
            initLC700Device();
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
//        alert('Connection fail(' + jqXHR.status + ')!');
        alert('未检测到[蒙恬电子签名板],请更换USB接口或关闭杀毒饮件试试，若仍有问题请联络蒙恬客服 !');
    });
}

function initLC700Device() {
    $.ajax({
        url: initLC700Url,
        type: 'GET',
        cache: false
    }).done(function (response) {
        if (response === true) {
            isPolling = true;
            isLC700Connected = true;

            getInk();
            getStatus();

            $('.init').removeAttr('disabled');
            $('#initBtn').attr('disabled', 'disabled');
        } else {
            initE640Device();
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
//        alert('Connection fail(' + jqXHR.status + ')!');
        alert('未检测到[蒙恬电子签名板],请更换USB接口或关闭杀毒饮件试试，若仍有问题请联络蒙恬客服 !');
    });
}

function initE640Device() {
    $.ajax({
        url: initE640Url,
        type: 'GET',
        cache: false
    }).done(function (response) {
        if (response === true) {
            isPolling = true;
            isE640Connected = true;

            getInk();
            getStatus();

            $('.init').removeAttr('disabled');
            $('#initBtn').attr('disabled', 'disabled');
        } else {
            alert('未检测到[蒙恬电子签名板],请更换USB接口或关闭杀毒饮件试试，若仍有问题请联络蒙恬客服 !');
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
//        alert('Connection fail(' + jqXHR.status + ')!');
        alert('未检测到[蒙恬电子签名板],请更换USB接口或关闭杀毒饮件试试，若仍有问题请联络蒙恬客服 !');
    });
}

// uninitialize device
function uninitDevice() {
    isPolling = false;
    var uninitDeviceUrl = uninitUrl;

    if (isL500Connected === true) {
        uninitDeviceUrl = uninitL500Url;
    } else if (isL501GConnected === true) {
        uninitDeviceUrl = uninitL501GUrl;
    } else if (isLC700Connected === true) {
        uninitDeviceUrl = uninitLC700Url;
    } else if (isE640Connected === true) {
        uninitDeviceUrl = uninitE640Url;
    }

    $.ajax({
        url: uninitDeviceUrl,
        type: 'GET',
        cache: false
    }).done(function (response) {
        if (response === true) {

            var canvas = document.getElementById('ppCanvas');
            context.clearRect(0, 0, canvas.width, canvas.height);

            $('.init').attr('disabled', 'disabled');
            $('#initBtn').removeAttr('disabled');
        };
    });

    isL500Connected = false;
    isLC700Connected = false;
    isE640Connected = false;
}

// initialize canvas and setup context
window.onload = function () {
    canvas = document.getElementById('ppCanvas');

    if (canvas.getContext) {
        context = canvas.getContext('2d');
    }
};

window.onbeforeunload = function (e) {
    uninitDevice();
    var milliseconds = 500;
    var start = new Date().getTime();

    while (true) {
        if (new Date().getTime() - start > milliseconds) {
            break;
        }
    }
};

function getStatus() {
    // 用polling的方式向self-host發送request取得簽名板按鈕status
    (function poll() {
        var timeId = setTimeout(function () {

            clearTimeout(timeId);

            // 取得狀態
            if (isPolling) {
                $.ajax({
                    url: confirmStatusUrl,
                    type: 'GET',
                    cache: false
                }).done(function (result) {
                    if (result == '1') {
                        var canvas = document.getElementById('ppCanvas');
						context.clearRect(0, 0, canvas.width, canvas.height);
                        saveDrawing();
                    } else if (result == '0') {
                        clearInk();
                    }
                }).fail(function () {
                    console.log('Fail to get confirmed status!');
                }).always(function () {
                    if (isPolling) {
                        poll();
                    } else {}
                });
            }
        }, 500);
    })();
};

function getInk() {
    // 用polling的方式向self-host發送request取得簽名板畫面(base64格式)
    (function poll() {
        var timeId = setTimeout(function () {

            clearTimeout(timeId);

            if (isPolling) {
                $.ajax({
                    url: getInkUrl,
                    type: 'GET',
                    cache: false
                }).done(function (data) {
                    var dataInfos = JSON.parse(data);

                    dataInfos.forEach(function (value) {
                        if (value.EventType === 0) {
                            drawImage(value.Image);
                            LastSignatureBase64Data = value.Image;
                        }
                    });
                }).always(function () {
                    if (isPolling) {
                        poll();
                    } else {}
                });
            }
        }, 50);
    })();
};

function drawImage(base64) {
    var dataUrl = 'data:image/png;base64,';

    dataUrl = dataUrl + base64;

    // 在image中載入圖檔，再畫到canvas呈現
    var img = new Image();

    img.addEventListener('load', function () {
        context.drawImage(this, 0, 0, canvas.width, canvas.height);
    }, false);

    img.src = dataUrl;
};

// clear Ink
function clearInk() {

    $.ajax({
        url: clrInkUrl,
        type: 'GET',
        cache: false,
        success: function success() {
            var canvas = document.getElementById('ppCanvas');
            context.clearRect(0, 0, canvas.width, canvas.height);
        }
    });
};

// save drawing images
function saveDrawing() {
    var getsdType = '2';    // jpeg type...
    var getsdDpi = '0';     // 150 dpi...
    var localPath = 'DrawImage_' + generateString(5);
    var sdT = '.JPG', sdD = 150;

    $.ajax({
        url: savedrawUrl + 'type=' + getsdType + '&dpi=' + getsdDpi + '&path=' + localPath + sdT,
        type: 'GET',
        cache: false
    }).done(function (resp) {
        clearInk();
        if (Boolean(parseInt(resp))) {
            alert('Save file ' + localPath + ' failed' + ', result=' + resp);
        } else {
            if (navigator.userAgent.indexOf("WOW64") != -1 || navigator.userAgent.indexOf("Win64") != -1) {
                alert('File：' + resp + ' saved\nDpi：' + sdD);
            } else {
                alert('File：' + resp + ' saved\nDpi：' + sdD);
            }
        }
    });
};

// Generate random number
function generateString(length) {
    var text = "";
    var possible = "0123456789";

    for (var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }return text;
}
