/**
 * Copyright (c) 2020
 *
 * CENTIRM HotelTV HCAP module javascript.
 *
 * @summary short description for the file
 * @author Joel <joel.kim@centirm.com>
 *
 * Created at     : 2020-11-26 02:21:56
 * Last modified  : 2020-11-26 15:31:40
 */

HotelTV.namespace('HotelTV.api');
HotelTV.api = (function() {
    //// 의존 관계 선언
    let _api_ver = Object.prototype.toString,
        _svr_ip = Object.prototype.toString,
        _serial_num = Object.prototype.toString,
        _dev_familly = Object.prototype.toString,
        _license = Object.prototype.toString,
        _token = "aLc*eBgTijklRnopq4s",
        _registered = false,
        _exist = false,
        _svr_port = 0,
        _1stBoot = false;

    //// 비공개 프로퍼티

    /// 초기화 루틴

    //// 비공개 매써드
    /**
     *
     */
    function __apifxn_init(param) {
        _api_ver = param.api_ver;
        _serial_num = param.serial_num;
        _svr_ip = param.svr_ip;
        _svr_port = param.svr_port;
        _dev_familly = param.dev_familly;
        _license = param.license;
        _token = param.apikey;
        _registered = param.registered;
        _exist = param.exist;
        _1stBoot = param.firstBoot;
    }


    /**
     * API Wrapper Function::> Get API base URI
     */
    function __apifxn_get_base_url() {
        var sz_base_url = "http://" + _svr_ip + ":" + _svr_port;
        return sz_base_url;
    }

    /**
     * API Wrapper Function::> Get Device License
     */
    function __apifxn_get_license() {
        return _license;
    }


    /**
     * API Wrapper Function::> Get Device Registered
     */
    function __apifxn_get_registered() {
        return { 'registered': _registered, 'exist': _exist, 'license': _license };
    }

    /**
     * API Wrapper Function::> Get API Token
     */
    function __apifxn_get_token() {
        return _token;
    }


    /**
     * API Wrapper Function::> Get ProCentric Server Info(Realted HCAP API:hcap.system.getProcentricServer)
     */
    function __apifxn_get_api_url(api_type) {
        var dic_api_url = {
            "get_translation": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/translation",
            "get_device_settings": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/setting",
            "get_site_info": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/info",
            "get_guest_info": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/guest",
            "get_opening_ctz": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/opening",
            "get_amenity_ctz": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/amentity",
            "get_roomservice_ctz": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/roomService",
            "get_widget_ctz": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/widget",
            "get_program_ctz": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/program",
            "get_epg_info": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/epg",
            "get_weather": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/weather",
            "get_flight": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/flight",
            "get_services": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/services",
            "get_news": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/news",
            "get_message": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/messages",
            /* Requests */
            "get_carts_amenity": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/amenity/carts",
            "put_carts_amenity": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/amenity/carts",
            "update_carts_amenity": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/amenity/carts",
            "delete_carts_amenity": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/amenity/carts",
            "get_order_amenity": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/amenity/orders",
            "put_order_amenity": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/amenity/orders",
            "get_carts_roomservice": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/roomService/carts",
            "put_carts_roomservice": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/roomService/carts",
            "update_carts_roomservice": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/roomService/carts",
            "delete_carts_roomservice": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/roomService/carts",
            "get_order_roomservice": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/roomService/orders",
            "put_order_roomservice": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/requests/roomService/orders",
            /* Events */
            "update_event": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/event",
            /* Status */
            "set_device_status": __apifxn_get_base_url() + "/api/" + _api_ver + "/assets/" + _dev_familly + "/" + _serial_num + "/state",
            /*
            "get_emergency": __apifxn_get_base_url() + "/api/" + _api_ver + "/settops/" + _serial_num + "/emergency",
            "set_message_status": __apifxn_get_base_url() + "/api/" + _api_ver + "/settops/" + _serial_num + "/messages",

            "set_device_opmode": __apifxn_get_base_url() + "/api/" + _api_ver + "/settops/" + _serial_num + "/bbdoors/opmode",
            */
        }

        if (api_type in dic_api_url) {
            return dic_api_url[api_type];
        }
        return null;
    }


    function __apifxn_CallCmsApi(_method, sz_url, api_type, dic_param) {
        return new Promise((resolve, reject) => {
            let isPostMsg = false;
            let xhr = new XMLHttpRequest();
            // let formData = new FormData();
            let _ret = { type: api_type, error: true, reason: null, data: null };

            //xhr.timeout = 500;
            if (dic_param !== null) {
                isPostMsg = true;
                // for (_key in dic_param) {
                //     formData.append(_key.toString(), dic_param[_key]);
                // }
            }

            xhr.onload = function() {
                if (xhr.status === 200 || xhr.status === 201) {
                    _ret.error = false;
                    _ret.data = xhr.response;
                    resolve(_ret);
                } else {
                    reject(_ret);
                }
            };

            xhr.ontimeout = function(e) {
                // XMLHttpRequest timed out. Do something here.
                _ret.reason = "TIMEOUT";
                reject(_ret);
            };

            xhr.onerror = function() {
                _ret.reason = "FATAL";
                reject(_ret);
            }

            switch (_method) {
                case "GET":
                    xhr.open('GET', sz_url, true);
                    xhr.setRequestHeader("Accept", "application/json");
                    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    xhr.setRequestHeader("Authorization", "Bearer " + __apifxn_get_token());
                    xhr.send(null);
                    break;
                case "POST":
                    xhr.open('POST', sz_url);
                    xhr.setRequestHeader("Accept", "application/json");
                    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    xhr.setRequestHeader("Authorization", "Bearer " + __apifxn_get_token());
                    xhr.send(JSON.stringify(dic_param)); // 폼 데이터 객체 전송
                    break;
                case "PATCH":
                    xhr.open('PATCH', sz_url);
                    xhr.setRequestHeader("Accept", "application/json");
                    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    xhr.setRequestHeader("Authorization", "Bearer " + __apifxn_get_token());
                    xhr.send(JSON.stringify(dic_param)); // 폼 데이터 객체 전송
                    break;
                case "DELETE":
                    xhr.open('DELETE', sz_url, true);
                    xhr.setRequestHeader("Accept", "application/json");
                    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                    xhr.setRequestHeader("Authorization", "Bearer " + __apifxn_get_token());
                    xhr.send(null);
                    break;
            }
        });
    }



    //// 공개 API
    return {
        Init: function(ip, port, model, serial) {
            return new Promise((resolve, reject) => {
                if (HotelTV.state.token) {
                    let _token = HotelTV.state.token;
                    __apifxn_init({ 'dev_familly': model, 'serial_num': serial, 'svr_ip': ip, 'svr_port': port, 'api_ver': _token.version, "license": _token.license, "apikey": _token.apikey, "registered": _token.registered, "exist": _token.exist, "firstBoot": false });
                    resolve(0);
                } else {
                    // licenses api format
                    // <svr ip:svr port>/api/licenses/us761h0n/103INLV4B896
                    var sz_api_url = "http://" + ip + ":" + port + "/api/licenses" + "/" + model + "/" + serial;
                    console.log("Debug: request token url:" + sz_api_url);
                    __apifxn_CallCmsApi("GET", sz_api_url, "GetToken", null).then(_result => {
                        //console.log(`Success::>${_result.data}`);
                        HotelTV.state.token = JSON.parse(_result.data);
                        __apifxn_init({ 'dev_familly': model, 'serial_num': serial, 'svr_ip': ip, 'svr_port': port, 'api_ver': HotelTV.state.token.version, "license": HotelTV.state.token.license, "apikey": HotelTV.state.token.apikey, "registered": HotelTV.state.token.registered, "exist": HotelTV.state.token.exist, "firstBoot": HotelTV.state.token.firstBoot });
                        resolve(0);
                    }).catch(_error => {
                        console.error(`Failure::>${_error.reason}`);
                        reject(_error.reason);
                    });
                }
            });
        },

        GetBaseUrl: function() {
            return __apifxn_get_base_url();
        },

        CheckRegistration: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_registered();
                resolve(sz_api_url);
            });
        },

        DownloadData: function(dl_url) {
            return new Promise((resolve, reject) => {
                __apifxn_CallCmsApi("GET", dl_url, "DownloadData", null).then(_result => {
                    resolve(_result.data);
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetTranslation: function(group, locale) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_translation");
                //let sz_api_param = null;
                if (group) {
                    sz_api_url += `/&group=${group};`;
                }
                if (locale) {
                    sz_api_url += `/&locales=${locale};`;
                }
                __apifxn_CallCmsApi("GET", sz_api_url, "GetTranslation", null).then(_result => {
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetServiceInfo: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_services");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetServiceInfo", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetSettings: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_device_settings");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetDeviceSettings", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetHotelInfo: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_site_info");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetHotelInfo", null).then(_result => {
                    ///console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetGuestInfo: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_guest_info");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetGuestInfo", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetOpeningCtz: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_opening_ctz");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetOpeningCtz", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetAmenityCtz: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_amenity_ctz");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetAmenityCtz", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetRoomServiceCtz: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_roomservice_ctz");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetRoomServiceCtz", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetWeather: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_weather");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetWeather", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetFlight: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_flight");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetFlight", null).then(_result => {
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetWidgetCtz: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_widget_ctz");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetWidgetCtz", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetProgramCtz: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_program_ctz");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetProgramCtz", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetEpg: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_epg_info");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetEpg", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetNews: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_news");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetNews", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        GetMessage: function() {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_message");
                __apifxn_CallCmsApi("GET", sz_api_url, "GetMessage", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        SetMessageStatus: function(msgID) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_message") + "/" + msgID;
                __apifxn_CallCmsApi("GET", sz_api_url, "SetMessageStatus", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    let _rspJson = JSON.parse(_result.data);
                    if (_rspJson.status == 'ok') {
                        resolve(_rspJson.data);
                    } else {
                        resolve(null);
                    }
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> get amenity carts info
         * @param {dictionary} _item_id if _item_id isn't null it will return specified info with _item_id
         */
        GetAmenityCarts: function(_item_id) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_carts_amenity");
                __apifxn_CallCmsApi((_item_id) ? "POST" : "GET", sz_api_url, "GetAmenityCarts", _item_id).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> put amenity carts info
         * @param {dictionary} _item_id if _item_id isn't null it will return specified info with _item_id
         */
        PutAmenityCarts: function(_item_id, _quantity) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("put_carts_amenity");
                __apifxn_CallCmsApi("POST", sz_api_url, "PutAmenityCarts", { "itemId": _item_id, "quantity": _quantity }).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> update amenity carts info
         * @param {dictionary} _cart_id if _item_id isn't null it will return specified info with _item_id
         */
        UpdateAmenityCarts: function(_cart_id, _quantity) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("update_carts_amenity");
                __apifxn_CallCmsApi("PATCH", `${sz_api_url}/${_cart_id}`, "UpdateAmenityCarts", { "quantity": _quantity }).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> delete amenity carts info
         * @param {dictionary} _cart_id if _item_id isn't null it will return specified info with _item_id
         */
        DeleteAmenityCarts: function(_cart_id) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("delete_carts_amenity");
                __apifxn_CallCmsApi("DELETE", `${sz_api_url}/${_cart_id}`, "DeleteAmenityCarts", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> get amenity order info
         * @param {dictionary} _item_id if _item_id isn't null it will return specified info with _item_id
         */
        GetAmenityOrders: function(_item_id) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_order_amenity");
                __apifxn_CallCmsApi((_item_id) ? "POST" : "GET", sz_api_url, "GetAmenityOrders", _item_id).then(_result => {
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> order amenity
         * @param {dictionary} _cart_id if _item_id isn't null it will return specified info with _item_id
         */
        PutAmenityOrders: function(_cart_item) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("put_order_amenity");
                __apifxn_CallCmsApi("POST", `${sz_api_url}`, "PutAmenityOrders", _cart_item).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> get room service carts info
         * @param {dictionary} _item_id if _item_id isn't null it will return specified info with _item_id
         */
        GetRoomserviceCarts: function(_item_id) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_carts_roomservice");
                __apifxn_CallCmsApi((_item_id) ? "POST" : "GET", sz_api_url, "GetRoomserviceCarts", _item_id).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> put room service carts info
         * @param {dictionary} _item_id if _item_id isn't null it will return specified info with _item_id
         */
        PutRoomserviceCarts: function(_item_id, _quantity) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("put_carts_roomservice");
                __apifxn_CallCmsApi("POST", sz_api_url, "PutRoomserviceCarts", { "itemId": _item_id, "quantity": _quantity }).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> update room service carts info
         * @param {dictionary} _cart_id if _item_id isn't null it will return specified info with _item_id
         */
        UpdateRoomserviceCarts: function(_cart_id, _quantity) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("update_carts_roomservice");
                __apifxn_CallCmsApi("PATCH", `${sz_api_url}/${_cart_id}`, "UpdateRoomserviceCarts", { "quantity": _quantity }).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> delete room service carts info
         * @param {dictionary} _cart_id if _item_id isn't null it will return specified info with _item_id
         */
        DeleteRoomserviceCarts: function(_cart_id) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("delete_carts_roomservice");
                __apifxn_CallCmsApi("DELETE", `${sz_api_url}/${_cart_id}`, "DeleteRoomserviceCarts", null).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> get room service order info
         * @param {dictionary} _item_id if _item_id isn't null it will return specified info with _item_id
         */
        GetRoomserviceOrders: function(_item_id) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("get_order_roomservice");
                __apifxn_CallCmsApi((_item_id) ? "POST" : "GET", sz_api_url, "GetRoomserviceOrders", _item_id).then(_result => {
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        /**
         * HotelTV API ::> order room service
         * @param {dictionary} _cart_id if _item_id isn't null it will return specified info with _item_id
         */
        PutRoomserviceOrders: function(_cart_item) {
            return new Promise((resolve, reject) => {
                let sz_api_url = __apifxn_get_api_url("put_order_roomservice");
                __apifxn_CallCmsApi("POST", `${sz_api_url}`, "PutRoomserviceOrders", _cart_item).then(_result => {
                    //console.log(`Success::>${_result.data}`);
                    resolve(JSON.parse(_result.data));
                }).catch(_error => {
                    console.error(`Failure::>${_error.reason}`);
                    reject(_error.reason);
                });
            });
        },

        ReportEvent: function(_arrary_event) {
            let _json_event = {
                "events": [],
            };

            for (let _evtidx in _arrary_event) {
                _json_event.events.push({
                    "power": _arrary_event[_evtidx].power,
                    "location": _arrary_event[_evtidx].location,
                    "timestamp": Date.now()
                })
            }

            let sz_api_url = __apifxn_get_api_url("update_event");
            __apifxn_CallCmsApi("POST", sz_api_url, "UpdateEvent", _json_event).then(_result => {
                //console.log(`Success::>${_result.data}`);
            }).catch(_error => {
                console.error(`Failure::>${_error.reason}`);
            });
        },

        ReportBrief: function(_dev_inf, _gst_info, _usage_inf) {
            let _json_report = {
                "updated": "YYYY-MM-DD HH:MM:SS",
                "brnote": "IN-SERVICE",
                "guest_language": "",
                "guest_name": "Jason Smith",
                "guest_checkin": "1899-12-31",
                "guest_checkout": "1899-12-31",
                "guest_roomid": "7635",
                "ker_ver": "0.00.00",
                "cpu_usage": [],
                "free_mem": null,
                "disk_space_free": {
                    "flash": { "total": 0, "free": 0, "used": 0, "percent": "0" },
                    "storage": { "total": 0, "free": 0, "used": 0, "percent": "0" }
                },
                "cpu_freq": { "current": 0, "min": 0, "max": 0 },
                "ip_addr": "xxx.xxx.xxx.xxx",
                "mac_addr": "",
                "mac_wifi": "",
                "mac_bt": "",
                "speed": 0,
                "manufacture": "LG",
                "model": "",
                "hw_ver": "1.00",
                "sw_ver": "1.1.5",
                "scr_resolution": "1920x1080@60.00Hz - Full screen",
                "temp": 0,
                "uptime": {
                    "second": 344632,
                    "string": "03d23h43m52s"
                },
                "api_ver": "v1"
            };

            const _fxn_cvtDateFmt1 = function(_date) {
                var _year = _date.getFullYear();
                var _month = _date.getMonth() + 1;
                if (_month < 10) _month = '0' + _month;
                var _day = _date.getDate();
                if (_day < 10) _day = '0' + _day;
                var _hour = _date.getHours();
                if (_hour < 10) _hour = '0' + _hour;
                var _min = _date.getMinutes();
                if (_min < 10) _min = '0' + _min;
                var _sec = _date.getSeconds();
                if (_sec < 10) _sec = '0' + _sec;
                return _year + "-" + _month + "-" + _day + " " + _hour + ":" + _min + ":" + _sec;
            };

            const _fxn_sec2Date = function toDateTime(secs) {
                var __t = new Date(1970, 0, 1); // Epoch
                __t.setSeconds(secs);
                var _day = (__t.getDate() - 1);
                if (_day < 10) _day = '0' + _day;
                var _hour = __t.getHours();
                if (_hour < 10) _hour = '0' + _hour;
                var _min = __t.getMinutes();
                if (_min < 10) _min = '0' + _min;
                var _sec = __t.getSeconds();
                if (_sec < 10) _sec = '0' + _sec;
                return _day + "d" + _hour + "h" + _min + "m" + _sec + "s";
            }
            _json_report.updated = _fxn_cvtDateFmt1(new Date());
            _json_report.ker_ver = _dev_inf.boot_version.major + "." + _dev_inf.boot_version.minor + "." + _dev_inf.boot_version.revision;
            _json_report.cpu_usage = [_usage_inf.cpu];
            _json_report.brnote = 'IN-SERVICE';
            _json_report.free_mem = {
                "available": 0,
                "inactive": 0,
                "cached": 0,
                "shared": 0,
                "total": (_usage_inf.mem.total * 1048576),
                "percent": _usage_inf.mem.percent.toString(),
                "free": (_usage_inf.mem.free * 1048576),
            };
            _json_report.guest_language = _gst_info.language;
            _json_report.guest_name = _gst_info.name;
            _json_report.guest_checkin = _gst_info.cidt;
            _json_report.guest_checkout = _gst_info.codt;
            _json_report.guest_roomid = _gst_info.roomid;
            _json_report.ip_addr = _dev_inf.network_info.ip_address;
            _json_report.mac_addr = _dev_inf.network_info.details[0].mac;
            _json_report.mac_wifi = _dev_inf.network_info.details[1].mac;
            _json_report.mac_bt = '';

            _json_report.model = _dev_inf.model_name;
            _json_report.hw_ver = _dev_inf.hardware_version.major + "." + _dev_inf.hardware_version.minor;
            _json_report.sw_ver = _dev_inf.hcap_middleware_version.major + "." + _dev_inf.hcap_middleware_version.minor + "." + _dev_inf.hcap_middleware_version.revision;
            _json_report.scr_resolution = _dev_inf.display_resolution;

            _json_report.uptime.second = Math.floor(_dev_inf.uptime / 1000);
            _json_report.uptime.string = _fxn_sec2Date(_json_report.uptime.second);

            let sz_api_url = __apifxn_get_api_url("set_device_status");
            __apifxn_CallCmsApi("PATCH", sz_api_url, "SetDeviceStatus", _json_report).then(_result => {
                //console.log(`Success::>${_result.data}`);
            }).catch(_error => {
                console.error(`Failure::>${_error.reason}`);
            });
        },
    }
})();