protected void SendCommandImmediately(ServiceCommand command)
        {
            var headers = new JsonObject();
            var payload = (JsonObject)command.Payload;
            var payloadType = "";

            try
            {
                if (payload != null && payload.ContainsKey("type"))
                    payloadType = payload.GetNamedString("type");
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {
                // ignore
            }

            if (payloadType == "p2p")
            {
                foreach (var key in payload.Select(pair => pair.Key))
                {
                    try
                    {
                        if (payload != null) headers.Add(key, payload.GetNamedObject(key));
                    }
                    // ReSharper disable once EmptyGeneralCatchClause
                    catch
                    {
                        // ignore
                    }
                }
                SendMessage(headers, null);
            }
            else if (payloadType == "hello")
            {
                if (payload != null)
                {
                    var message = payload.Stringify();
                    try
                    {
                        messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
                        messageWebSocket.OutputStream.FlushAsync().GetResults();
                        if (dr == null)
                            dr = new DataWriter(messageWebSocket.OutputStream);
                        dr.WriteString(message);
                        dr.StoreAsync();
                        Debug.WriteLine("{0} : {1} : {2}", DateTime.Now, "sent", message);
                    }
                    // ReSharper disable once EmptyGeneralCatchClause
                    catch
                    {

                    }
                }
            }
            else
            {
                try
                {
                    headers.Add("type", JsonValue.CreateStringValue(command.HttpMethod));
                    headers.Add("id", JsonValue.CreateStringValue(command.RequestId.ToString()));
                    headers.Add("uri", JsonValue.CreateStringValue(command.Target));

                }
                // ReSharper disable once EmptyGeneralCatchClause
                catch (Exception)
                {
                    // TODO: handle this
                }


                SendMessage(headers, payload);
            }

        }
        protected void SendRegister()
        {
            var requestListener = new ResponseListener
            (
                loadEventArg =>
                {

                },
                serviceCommandError =>
                {
                    if (Listener != null)
                        Listener.OnRegistrationFailed(serviceCommandError);
                }
            );

            var dataId = nextRequestId++;

            var command = new ServiceCommand(this, null, null, requestListener) { RequestId = dataId };

            var headers = new JsonObject();
            var payload = new JsonObject();

            try
            {
                headers.Add("type", JsonValue.CreateStringValue("register"));
                headers.Add("id", JsonValue.CreateNumberValue(dataId));

                if (!(service.ServiceConfig is WebOsTvServiceConfig))
                {
                    service.ServiceConfig = new WebOsTvServiceConfig(service.ServiceConfig.ServiceUuid);
                }

                if (((WebOsTvServiceConfig)service.ServiceConfig).ClientKey != null)
                {
                    payload.Add("client-key", JsonValue.CreateStringValue(((WebOsTvServiceConfig)service.ServiceConfig).ClientKey));
                }
                else
                {
                    if (Listener != null)
                        Listener.OnBeforeRegister(PairingType.NONE);
                }

                if (manifest != null)
                {
                    payload.Add("manifest", manifest);
                }
            }
            catch (Exception e)
            {
                // ReSharper disable once PossibleIntendedRethrow
                throw e;
            }

            Requests.Add(dataId, command);

            SendMessage(headers, payload);
        }
        public void SendCommand(ServiceCommand command)
        {
            int requestId;
            if (command.RequestId == -1)
            {
                requestId = nextRequestId++;
                command.RequestId = requestId;
            }
            else
            {
                requestId = command.RequestId;
            }

            Requests.Add(requestId, command);
            try
            {
                if (state == State.Registered)
                {
                    this.SendCommandImmediately(command);
                }
                else if (state == State.Connecting || state == State.Disconnecting)
                {
                    
                    commandQueue.Enqueue(command);
                }
                else
                {
                    commandQueue.Enqueue(command);
                    Connect();
                }
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch
            {

            }
        }
        private void HelloTv()
        {
            //Context context = DiscoveryManager.getInstance().getContext();
            //PackageManager packageManager = context.getPackageManager();

            // app Id

            var packageName = Package.Current.Id.Name;

            //// SDK Version
            String sdkVersion = DiscoveryManager.ConnectSdkVersion;

            var deviceInfo = new EasClientDeviceInformation();

            //// Device Model
            var deviceModel = deviceInfo.FriendlyName;



            //// OS Version
            var osVersion = deviceInfo.OperatingSystem;



            //// resolution
            //WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            //Display display = wm.getDefaultDisplay();

            //@SuppressWarnings("deprecation")
            //int width = display.getWidth(); // deprecated, but still needed for supporting API levels 10-12

            //@SuppressWarnings("deprecation")
            //int height = display.getHeight(); // deprecated, but still needed for supporting API levels 10-12

            //var screenResolution = String.Format("%{0}x%{1}", 1680, 1050); 

            //// app Name
            //ApplicationInfo applicationInfo;
            //try {
            //    applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
            //} catch (final NameNotFoundException e) {
            //    applicationInfo = null;
            //}
            //String applicationName = (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "(unknown)");

            //// app Region
            //Locale current = context.getResources().getConfiguration().locale;
            //String appRegion = current.getDisplayCountry();

            var payload = new JsonObject();
            try
            {
                payload.SetNamedValue("sdkVersion", JsonValue.CreateStringValue(sdkVersion));
                payload.SetNamedValue("deviceModel", JsonValue.CreateStringValue(deviceModel));
                payload.SetNamedValue("OSVersion", JsonValue.CreateStringValue(osVersion));
                //payload.SetNamedValue("resolution", JsonValue.CreateStringValue(resolution));
                //payload.SetNamedValue("appId", JsonValue.CreateStringValue(appId));
                payload.SetNamedValue("appName", JsonValue.CreateStringValue(packageName));
                //payload.SetNamedValue("appRegion", JsonValue.CreateStringValue(appRegion));
            }
            catch (Exception e)
            {
                throw e;
            }

            var dataId = nextRequestId++;

            var sendData = new JsonObject();
            try
            {
                sendData.SetNamedValue("id", JsonValue.CreateNumberValue(dataId));
                sendData.SetNamedValue("type", JsonValue.CreateStringValue("hello"));
                sendData.SetNamedValue("payload", payload);
            }
            catch (Exception e)
            {
                throw e;
            }

            var request = new ServiceCommand(this, null, sendData, null);
            SendCommandImmediately(request);
        }
        public override void Seek(long position, ResponseListener listener)
        {
            if (position < 0)
            {
                if (listener != null)
                    listener.OnError(new ServiceCommandError(0, null));

                return;
            }

            var requestIdNumber = GetNextId();
            var requestId = String.Format("req{0}", requestIdNumber);

            JsonObject message = null;
            try
            {
                message = new JsonObject {{"contentType", JsonValue.CreateStringValue(NamespaceKey + "mediaCommand")}};
                var mediaCommandObject = new JsonObject
                {
                    {"type", JsonValue.CreateStringValue("seek")},
                    {"position", JsonValue.CreateNumberValue((int)(position/1000))},
                    {"requestId", JsonValue.CreateStringValue(requestId)}
                };
                message.Add("mediaCommand", mediaCommandObject);
            }
            catch (Exception)
            {
                if (listener != null)
                    listener.OnError(new ServiceCommandError(0, null));
            }

            var command = new ServiceCommand(null, null, null, listener);

            mActiveCommands.TryAdd(requestId, command);

            SendMessage(message, listener);
        }
        public override void PlayMedia(String url, String mimeType, String title, String description, String iconSrc,
            bool shouldLoop, ResponseListener listener)
        {
            var requestIdNumber = GetNextId();
            var requestId = String.Format("req{0}", requestIdNumber);

            JsonObject message = null;
            try
            {
                message = new JsonObject {{"contentType", JsonValue.CreateStringValue(NamespaceKey + "mediaCommand")}};
                var mediaCommandObject = new JsonObject
                {
                    {"mimeType", JsonValue.CreateStringValue(mimeType)},
                    {"requestId", JsonValue.CreateStringValue(requestId)},
                    {"iconURL", JsonValue.CreateStringValue(iconSrc)},
                    {"title", JsonValue.CreateStringValue(title)},
                    {"type", JsonValue.CreateStringValue("playMedia")},
                    {"description", JsonValue.CreateStringValue(description)},
                    {"mediaURL", JsonValue.CreateStringValue(url)},
                    {"shouldLoop", JsonValue.CreateBooleanValue(shouldLoop)},
                };

                message.Add("mediaCommand", mediaCommandObject);
            }
            catch (Exception)
            {
                if (listener != null)
                    listener.OnError(new ServiceCommandError(0, null));
            }

            var responseListener = new ResponseListener
            (
                loadEventArg => Util.PostSuccess(listener, new MediaLaunchObject(LaunchSession, GetMediaControl())),
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            var command = new ServiceCommand(Socket, null, null, responseListener);

            mActiveCommands.TryAdd(requestId, command);

            var messageResponseListener = new ResponseListener
            (
                loadEventArg => { },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            SendP2PMessage(message, messageResponseListener);
        }
        public override void GetPosition(ResponseListener listener)
        {
            var requestIdNumber = GetNextId();
            var requestId = String.Format("req{0}", requestIdNumber);

            JsonObject message = null;
            try
            {
                message = new JsonObject {{"contentType", JsonValue.CreateStringValue(NamespaceKey + "mediaCommand")}};
                var mediaCommandObject = new JsonObject
                {
                    {"type", JsonValue.CreateStringValue("getPosition")},
                    {"requestId", JsonValue.CreateStringValue(requestId)}
                };
                message.Add("mediaCommand", mediaCommandObject);
            }
            catch (Exception)
            {
                if (listener != null)
                    listener.OnError(new ServiceCommandError(0, null));
            }

            var commandResponseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    try
                    {
                        var position = ((loadEventArg as LoadEventArgs).Load.GetPayload() as JsonObject).GetNamedNumber("position");

                        if (listener != null)
                            listener.OnSuccess(position * 1000);
                    }
                    catch (Exception)
                    {
                        if (listener != null) listener.OnError(new ServiceCommandError(0, null));
                    }
                },
                serviceCommandError =>
                {
                    if (listener != null)
                        listener.OnError(serviceCommandError);
                }
            );

            var command = new ServiceCommand(null, null, null, commandResponseListener);
            mActiveCommands.TryAdd(requestId, command);

            var messageResponseListener = new ResponseListener
            (
                loadEventArg =>
                {

                },
                serviceCommandError =>
                {
                    if (listener != null)
                        listener.OnError(serviceCommandError);
                }
            );

            SendMessage(message, messageResponseListener);
        }
        private void SendData()
        {
            waiting = true;

            String uri;
            var typeTest = toSend[0];

            var payload = new JsonObject();

            if (typeTest.Equals(EnterKey))
            {
                toSend.RemoveAt(0);
                uri = "ssap://com.webos.service.ime/sendEnterKey";
            }
            else if (typeTest.Equals(DeleteKey))
            {
                uri = "ssap://com.webos.service.ime/deleteCharacters";

                int count = 0;
                while (toSend.Count > 0 && toSend[0].Equals(DeleteKey))
                {
                    toSend.RemoveAt(0);
                    count++;
                }

                try
                {
                    payload.Add("count", JsonValue.CreateNumberValue(count));
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                uri = "ssap://com.webos.service.ime/insertText";
                var sb = new StringBuilder();

                while (toSend.Count > 0 && !(toSend[0].Equals(DeleteKey) || toSend[0].Equals(EnterKey)))
                {
                    var text = toSend[0];
                    sb.Append(text);
                    toSend.RemoveAt(0);
                }

                try
                {
                    payload.Add("text", JsonValue.CreateStringValue(sb.ToString()));
                    payload.Add("replace", JsonValue.CreateNumberValue(0));
                }
                catch (Exception e)
                {
                    throw e;
                }
            }

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    waiting = false;
                    if (toSend.Count > 0)
                        SendData();
                },
                serviceCommandError =>
                {
                    throw new NotImplementedException();
                }
            );

            var request = new ServiceCommand(service, uri, payload, responseListener);
            request.Send();
        }