Наследование: System.EventArgs
        async void chimneyMpdServer_OnPlaylistInfo(object sender, ResponseEventArgs e)
        {
            var currentPlaylist = await Dbconnection.QueryAsync<CurrentPlaylist>("SELECT * FROM CurrentPlaylist ORDER BY PositionId");

            string response = string.Empty;

            foreach(CurrentPlaylist cp in currentPlaylist)
            {
                if (cp.IsUri)
                {
                    response += "file: " + cp.Uri + "\n";
                    response += "Pos: " + cp.PositionId + "\n";
                }
                else
                {
                    var file = await Dbconnection.FindAsync<File>(o => o.FileId == cp.FileId);
                    if (file != null)
                    {
                        file.Pos = cp.PositionId;
                        await Dbconnection.UpdateAsync(file);

                        response += file.ToResponseString();
                    }
                }
            }
            chimneyMpdServer.AppendResponse(response, e.id, e.position);
        }
        async void chimneyMpdServer_OnPlaylistClear(object sender, ResponseEventArgs e)
        {
            string playlistName = null;

            if (e.arguments.Count > 0)
            {
                playlistName = e.arguments[0];
            }

            if(playlistName != null)
            {
                var playlistToClear = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName);

                if (playlistToClear != null)
                {
                    await Dbconnection.QueryAsync<PlaylistFile>("DELETE FROM PlaylistFiles WHERE PlaylistId = " + playlistToClear.PlaylistId);

                    playlistToClear.LastModified = DateTime.Now.ToString("s");

                    await Dbconnection.UpdateAsync(playlistToClear);
                }

            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("stored_playlist"));
        }
        async void chimneyMpdServer_OnRename(object sender, ResponseEventArgs e)
        {
            if (e.arguments.Count > 1)
            {
                string oldName = e.arguments[0];
                string newName = e.arguments[1];

                var renamePlaylists = await Dbconnection.FindAsync<Playlist>(o => o.Name == oldName);
                if(renamePlaylists != null)
                {
                    renamePlaylists.Name = newName;
                    renamePlaylists.LastModified = DateTime.Now.ToString("s");
                    await Dbconnection.UpdateAsync(renamePlaylists);
                }
            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("stored_playlist"));

        }
        async void chimneyMpdServer_OnLoad(object sender, ResponseEventArgs e)
        {
            string playlistName = string.Empty;

            int start = 0;
            int end = 0;

            bool suc = false;

            if (e.arguments.Count > 0)
            {
                playlistName = e.arguments[0];

                if (e.arguments.Count > 1)
                {
                    string[] par = e.arguments[1].Split(new char[] { ':' });
                    suc = int.TryParse(par[1], out start);

                    if (suc && par.Length > 1) suc = int.TryParse(par[2], out end);
                    else end = start;
                }
            }

            var playlistToAddFrom = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName);

            if(!suc && playlistToAddFrom != null)
            {
                end = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM PlaylistFiles WHERE PlaylistId = " + playlistToAddFrom.PlaylistId);
            }

            if(playlistToAddFrom != null)
            {
                var plFiles = await Dbconnection.QueryAsync<PlaylistFile>("SELECT * FROM PlaylistFiles WHERE PlaylistId = " + playlistToAddFrom.PlaylistId
                    + " AND Postion >= " + start + " AND Position < " + end);


                foreach(PlaylistFile plFile in plFiles)
                {
                    CurrentPlaylist newCurrentPlaylistItem = new CurrentPlaylist()
                    {
                        FileId = (plFile.IsUri) ? -1 : plFile.FileId,
                        IsUri = plFile.IsUri,
                        Uri = plFile.Uri,
                        PositionId = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM CurrentPlaylist")
                    };

                    await Dbconnection.InsertAsync(newCurrentPlaylistItem);
                }
            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("playlist"));
        }
        async void chimneyMpdServer_OnListPlaylists(object sender, ResponseEventArgs e)
        {
            var allPlaylists = await Dbconnection.QueryAsync<Playlist>("SELECT * FROM Playlists");

            string response = string.Empty;

            foreach(Playlist playlist in allPlaylists)
            {
                response += playlist.ToResponseString();
            }

            chimneyMpdServer.AppendResponse(response, e.id, e.position);
        }
 void chimneyMpdServer_OnDefault(object sender, ResponseEventArgs e)
 {
     chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
 }
        async void chimneyMpdServer_OnUpdate(object sender, ResponseEventArgs e)
        {
            string response = string.Empty;

            if (!is_db_updating)
            {
                is_db_updating = true;
                db_updating_id++;

                await UpdateDatabase();
            }

            response += "updating_db: " + db_updating_id;

            chimneyMpdServer.AppendResponse(response, e.id, e.position);
        }
        async void chimneyMpdServer_OnAdd(object sender, ResponseEventArgs e)
        {
            bool suc = true;

            string uri = string.Empty;

            File file = null;

            bool addasUri = false;

            if(e.arguments.Count > 0)
            {
                uri = e.arguments[0];

                file = await Dbconnection.FindAsync<File>(o => o.RelativePath.Equals(uri));

                if (file == null) addasUri = true;
            }

            if (file != null || addasUri)
            {
                CurrentPlaylist newCurrentPlaylistItem = new CurrentPlaylist()
                {
                    FileId = (addasUri) ? -1 : file.FileId,
                    IsUri = addasUri,
                    Uri = (addasUri) ? uri : file.FilePath,
                    Bitrate = (addasUri) ? 0 : file.Bitrate,
                    PositionId = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM CurrentPlaylist")
                };

                await Dbconnection.InsertAsync(newCurrentPlaylistItem);
            }
            else
            {
                //
                // Get the uri from arguments, if empty uri is empty
                //
                var directory = (e.arguments.Count > 0) ? await Dbconnection.Table<Directory>().Where(o => o.RelativePath.Equals(e.arguments[0])).FirstAsync() : null;

                //
                // Get the sub directories for the the uri directories
                //
                var subDirQuery = Dbconnection.Table<Directory>().Where(o => o.RelativePath.StartsWith(directory.RelativePath) || directory.RelativePath.Equals(string.Empty));
                var subDirectories = await subDirQuery.ToListAsync();
                foreach (Directory subdir in subDirectories)
                {
                    //
                    // Get all files in the current uri
                    //
                    var subfiles = await Dbconnection.QueryAsync<File>("SELECT * FROM Files WHERE Files.DirectoryId = " + subdir.DirectoryId);
                    foreach (File subfile in subfiles)
                    {
                        CurrentPlaylist newCurrentPlaylistItem = new CurrentPlaylist()
                        {
                            FileId = subfile.FileId,
                            PositionId = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM CurrentPlaylist")
                        };

                        await Dbconnection.InsertAsync(newCurrentPlaylistItem);
                    }
                }
            }


            if (suc) chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
            else
            {
                string errorfile = string.Empty;
                if (e.arguments.Count > 0) errorfile = e.arguments.First<string>();
                chimneyMpdServer.ErrorResponse(MPDKeyWords.Response.ACK + " [50@0] {add} could not add file:" + " \"" + errorfile + "\"", e.id, e.position);
            }

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("playlist"));

        }
        async void chimneyMpdServer_OnListAll(object sender, ResponseEventArgs e)
        {
            string response = string.Empty;

            //
            // Get the uri from arguments, if empty uri is empty
            //
            string uri = (e.arguments.Count > 0) ? e.arguments.First<string>() : string.Empty;

            //
            // Get the Directories with RelativePath of uri
            //
            var directories = await Dbconnection.QueryAsync<Directory>("SELECT * FROM Directories WHERE RelativePath = \"" + uri + "\"");
            
            foreach (Directory dir in directories)
            {
                //
                // Get the sub directories for the the uri directories
                //
                var subDirQuery = Dbconnection.Table<Directory>().Where(o => o.DirectoryId > 1 && (o.RelativePath.StartsWith(dir.RelativePath) || dir.RelativePath.Equals(string.Empty)));
                var subDirectories = await subDirQuery.ToListAsync();
                foreach (Directory subdir in subDirectories)
                {
                    response += subdir.ToReponseString();
                    //
                    // Get all files in the current uri
                    //
                    var subfiles = await Dbconnection.QueryAsync<File>("SELECT * FROM Files WHERE Files.DirectoryId = " + subdir.DirectoryId + " AND Type = \"File\"");
                    foreach (File file in subfiles)
                    {
                        response += file.ToSmallResponseString();
                    }
                }

                //
                // Get all files in the current uri
                //
                var files = await Dbconnection.QueryAsync<File>("SELECT * FROM Files WHERE Files.DirectoryId = " + dir.DirectoryId + " AND Type = \"File\"");
                foreach (File file in files)
                {
                    response += file.ToSmallResponseString();
                }
            }

            bool suc = true;

            if (suc) chimneyMpdServer.AppendResponse(response, e.id, e.position);
            else
            {
                string errorfile = string.Empty;
                if (e.arguments.Count > 0) errorfile = e.arguments.First<string>();
                chimneyMpdServer.ErrorResponse(MPDKeyWords.Response.ACK + " [50@0] {listall} could not find path:" + " \"" + errorfile + "\"", e.id, e.position);
            }
        }
        async void chimneyMpdServer_OnShuffle(object sender, ResponseEventArgs e)
        {
            //NowPlayingPlaylist.Shuffle();

            Random rng = new Random();
            var currentPlaylist = await Dbconnection.Table<CurrentPlaylist>().ToListAsync();

            foreach(CurrentPlaylist cp in currentPlaylist)
            {
                int k = rng.Next(currentPlaylist.Count -1);
                int pos = currentPlaylist[k].PositionId;
                currentPlaylist[k].PositionId = cp.PositionId;
                cp.PositionId = pos;
            }

            await Dbconnection.UpdateAllAsync(currentPlaylist);

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("playlist"));

        }
        async void chimneyMpdServer_OnConsume(object sender, ResponseEventArgs e)
        {
            if (e.arguments.Count > 0)
            {
                int newOptionSetting = 0;
                bool suc = int.TryParse(e.arguments.First<string>(), out newOptionSetting);

                var option = await Dbconnection.FindAsync<Option>(o => o.Name == "consume");

                if(option != null)
                {
                    option.ValueBool = (newOptionSetting == 0) ? false : true;
                    await Dbconnection.UpdateAsync(option);
                    option_consume = (newOptionSetting == 0) ? false : true;

                }
            }
            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("options"));

        }
        async void chimneyMpdServer_OnLsInfoOld(object sender, ResponseEventArgs e)
        {
            bool suc = true;

            var musicLibraryFolder = Windows.Storage.KnownFolders.MusicLibrary;

            string path = musicLibraryFolder.Name;

            string response = string.Empty;

            if (e.arguments.Count > 0) 
            {            
                path = e.arguments.First<string>();

                Tuple<StorageFolder, string> seekpath = new Tuple<StorageFolder,string>(musicLibraryFolder, musicLibraryFolder.Name);

                if (!path.Equals(musicLibraryFolder.Name.ToLower()))
                {
                    seekpath = await GetPath(musicLibraryFolder, path);
                }
                 
                var files = await seekpath.Item1.GetFilesAsync();
                var folders = await seekpath.Item1.GetFoldersAsync();

                response = string.Empty;

                foreach (StorageFolder folder in folders)
                {
                    response += "directory: " + seekpath.Item2 + "/" + folder.Name + "\n";
                }

                foreach (StorageFile file in files)
                {
                    if (file.FileType.ToLower().Equals(".mp3") ||
                        file.FileType.ToLower().Equals(".wav") ||
                        file.FileType.ToLower().Equals(".wma"))
                    {
                        //response += "file: " + seekpath.Item2 + "/" + file.Name + "\n";

                        SongTag songTag = await SongTag.GetSongTagFromFile(file);
                        songTag.file = seekpath.Item2 + "/" + file.Name;

                        response += songTag.ToString();

                    }
                }
            }
            else
            {
                foreach (Tuple<StorageFolder, string> rootpath in RootPaths)
                {
                    response += "directory: " + rootpath.Item2 + "\n";
                }
            }

            //if (suc) response = await FolderCrawler(seekpath.Item1, seekpath.Item2, false, true);
            
            if (suc) chimneyMpdServer.AppendResponse(response, e.id, e.position);
            else
            {
                string errorfile = string.Empty;
                if (e.arguments.Count > 0) errorfile = e.arguments.First<string>();
                chimneyMpdServer.ErrorResponse(MPDKeyWords.Response.ACK + " [50@0] {listall} could not find path:" + " \"" + errorfile + "\"", e.id, e.position);
            }
        }
        async void chimneyMpdServer_OnLsInfo(object sender, ResponseEventArgs e)
        {
            string response = string.Empty;
            bool suc = true;

            //
            // Get the uri from arguments, if empty uri is empty
            //

            string uri = (e.arguments.Count > 0) ? e.arguments.First<string>(): string.Empty;

            //
            // Get the Directories with RelativePath of uri
            //

            var directories = await Dbconnection.QueryAsync<Directory>("SELECT DirectoryId FROM Directories WHERE RelativePath = \"" + uri + "\"");
            foreach (Directory dir in directories)
            {
                //
                // Get the sub directories for the the uri directories
                //

                var subDirectories = await Dbconnection.QueryAsync<Directory>("SELECT * FROM Directories WHERE ParentDirectoryId = " + dir.DirectoryId);
                foreach (Directory subdir in subDirectories)
                {
                    response += subdir.ToReponseString();
                }

                //
                // Get all files in the current uri
                //

                var files = await Dbconnection.QueryAsync<File>("SELECT * FROM Files WHERE Files.DirectoryId = " + dir.DirectoryId + " AND Type = \"File\"");
                foreach (File file in files)
                {
                    response += file.ToResponseString();
                }
            }

            if (suc) chimneyMpdServer.AppendResponse(response, e.id, e.position);
            else
            {
                string errorfile = (e.arguments.Count > 0) ? e.arguments.First<string>() : string.Empty;
                chimneyMpdServer.ErrorResponse(MPDKeyWords.Response.ACK + " [50@0] {listall} could not find path:" + " \"" + errorfile + "\"", e.id, e.position);
            }
        }
        async void chimneyMpdServer_OnAddId(object sender, ResponseEventArgs e)
        {
            bool suc = false;

            int id = 0;

            File file = null;
  
            if (e.arguments.Count > 0)
            {
                string uri = e.arguments[0];
                //var files = await Dbconnection.QueryAsync<File>("SELECT * FROM Files WHERE RelativePath = \"" + uri + "\"");
                //file = (files.Count > 0) ? files[0] : null;

                file = await Dbconnection.FindAsync<File>(o => o.RelativePath.Equals(uri));

                //var query = Dbconnection.Table<File>().Where(o => o.RelativePath.Equals(uri));
                //file = await query.FirstAsync();
            }

            int position = -1;

            if (e.arguments.Count > 1) suc = int.TryParse(e.arguments[1], out position);
            else suc = false;

            position = (suc) ? position : -1;

            if (file != null)
            {
                int currentPlaylistCount = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM CurrentPlaylist");

                position = (position <= currentPlaylistCount && position >= 0) ? position : currentPlaylistCount;

                if (position != currentPlaylistCount)
                {
                    var affectedFiles = await Dbconnection.QueryAsync<CurrentPlaylist>("UPDATE CurrentPlaylist SET PositionId=PositionId+1 WHERE PositionId >= " + position);
                }

                CurrentPlaylist newCurrentPlaylistItem = new CurrentPlaylist()
                {
                    FileId = file.FileId,
                    PositionId = position,
                    Bitrate = file.Bitrate,
                    IsUri = false,
                    Uri = file.FilePath
                };

                await Dbconnection.InsertAsync(newCurrentPlaylistItem);

                suc = true;

                id = file.FileId;
            }
          
            if (suc) 
            {
                chimneyMpdServer.AppendResponse("Id: " + id + "\n", e.id, e.position);
            }
            else
            {
                string errorfile = string.Empty;
                if (e.arguments.Count > 0) errorfile = e.arguments.First<string>();
                chimneyMpdServer.ErrorResponse(MPDKeyWords.Response.ACK + " [50@0] {add} could not add file:" + " \"" + errorfile + "\"", e.id, e.position);
            }

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("playlist"));

        }
        async void chimneyMpdServer_OnCurrentSong(object sender, ResponseEventArgs e)
        {
            string response = string.Empty;

            if (!current_state.Equals("stop"))
            {
                //var currentSonga = await Dbconnection.QueryAsync<CurrentPlaylist>("SELECT * FROM CurrentPlaylist WHERE CurrentSong = 0");

                var currentSong = (await Dbconnection.QueryAsync<CurrentPlaylist>("SELECT * FROM CurrentPlaylist WHERE CurrentSong = 1")).FirstOrDefault<CurrentPlaylist>();

                if (currentSong != null)
                {
                    if (currentSong.IsUri)
                    {
                        response += "file: " + currentSong.Uri;
                        response += "Pos: " + currentSong.PositionId;
                    }
                    else
                    {
                        var currentFile = await Dbconnection.FindAsync<File>(o => o.FileId == currentSong.FileId);
                        if (currentFile != null)
                        {
                            currentFile.Pos = currentSong.PositionId;
                            response += currentFile.ToResponseString();
                        }
                    }
                }
            }

            chimneyMpdServer.AppendResponse(response, e.id, e.position);
        }
        async void chimneyMpdServer_OnClear(object sender, ResponseEventArgs e)
        {
            await Dbconnection.QueryAsync<CurrentPlaylist>("DELETE FROM CurrentPlaylist");

            List<string> returnevents = new List<string>();

            returnevents.Add("playlist");

            if(!current_state.Equals("stop"))
            {
                Stop();

                returnevents.Add("player");
            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs(returnevents));
        }
        async void chimneyMpdServer_OnStatus(object sender, ResponseEventArgs e)
        {
            string response = string.Empty;

            try
            {

#if WINDOWS_PHONE_APP
            response += "volume: " + Convert.ToInt32(BackgroundMediaPlayer.Current.Volume * 100) + "\n";
#else
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    response += "volume: " + Convert.ToInt32(ChimneyMPDMediaElement.Volume * 100) + "\n";
});
#endif
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
                response += "volume: 0\n";
            }

            response += (option_random) ? "random: 1\n" : "random: 0\n"; 
            response += (option_single) ? "single: 1\n" : "single: 0\n";
            response += (option_repeat) ? "repeat: 1\n" : "repeat: 0\n";
            response += (option_consume) ? "consume: 1\n" : "consume: 0\n";

            response += "playlist: " + await Dbconnection.ExecuteScalarAsync<int>("SELECT seq FROM sqlite_sequence WHERE name = \"CurrentPlaylist\"") + "\n";
            response += "playlistlength: " + await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM CurrentPlaylist") + "\n";

            var currentSong = await Dbconnection.FindAsync<CurrentPlaylist>(o => o.CurrentSong == true);

            if (current_state.Equals("play") || current_state.Equals("pause"))
            {
                response += "state: " + current_state + "\n"; 

                response += (currentSong != null) ? "song: " + currentSong.PositionId + "\n" : "song: 0\n";
                response += (currentSong != null) ? "songid: " + currentSong.FileId + "\n" : "songid: 0\n";

                if (currentSong != null)
                {
                    int nextpos = currentSong.PositionId + 1;

                    var nextSong = await Dbconnection.FindAsync<CurrentPlaylist>(o => o.PositionId == nextpos);

                    response += (nextSong != null) ? "nextsong: " + nextSong.PositionId + "\n" : string.Empty;
                    response += (nextSong != null) ? "nextsongid: " + nextSong.FileId + "\n" : string.Empty;
                }
                try
                { 
#if WINDOWS_PHONE_APP
                response += (BackgroundMediaPlayer.Current.Position != null) ? "time: " + BackgroundMediaPlayer.Current.Position.TotalSeconds + "\n" : "time: 0\n";
                response += (BackgroundMediaPlayer.Current.Position != null) ? "elapsed: " + BackgroundMediaPlayer.Current.Position.TotalSeconds + "\n" : "elapsed: 0\n";
#else
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    response += (ChimneyMPDMediaElement.Position != null) ? "time: " + ChimneyMPDMediaElement.Position.TotalSeconds + "\n" : "time: 0\n";
    response += (ChimneyMPDMediaElement.Position != null) ? "elapsed: " + ChimneyMPDMediaElement.Position.TotalSeconds + "\n" : "elapsed: 0\n";
});
#endif
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    response += "time: 0\n";
                    response += "elapsed: 0\n";
                }
                response += (currentSong != null) ? "bitrate: " + currentSong.Bitrate + "\n" : "bitrate: " + 0 + "\n";

                response += "xfade: 0\n";
                response += "mixrampdb: 0.000000\n";
                response += "mixrampdelay: 0\n";
                response += "audio: 16:44000:2\n";
            }
            else
            {
                response += "state: stop\n";
                response += "xfade: 0\n";
            }

            response += (is_db_updating) ? "updating_db: " + db_updating_id + "\n" : string.Empty;

            chimneyMpdServer.AppendResponse(response, e.id, e.position);
        }
        async void chimneyMpdServer_OnNext(object sender, ResponseEventArgs e)
        {
            var currentPlaylist = (await Dbconnection.QueryAsync<CurrentPlaylist>("SELECT * FROM CurrentPlaylist WHERE CurrentSong = 1")).FirstOrDefault<CurrentPlaylist>();

            if (currentPlaylist != null)
            {
                var nextPlaylist = (await Dbconnection.QueryAsync<CurrentPlaylist>("SELECT * FROM CurrentPlaylist WHERE Position = " + currentPlaylist.PositionId + 1)).FirstOrDefault<CurrentPlaylist>();

                if(nextPlaylist != null)
                {
                    Play(nextPlaylist.Uri, nextPlaylist.IsUri);

                    currentPlaylist.CurrentSong = false;
                    nextPlaylist.CurrentSong = true;

                    await Dbconnection.UpdateAsync(currentPlaylist);
                    await Dbconnection.UpdateAsync(nextPlaylist);
                }
            }
            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("player"));

        }
        async void chimneyMpdServer_OnSeekCur(object sender, ResponseEventArgs e)
        {
            bool suc = false;

            bool canseek = false;

#if WINDOWS_PHONE_APP
            canseek = BackgroundMediaPlayer.Current.CanSeek;
#else
            try
            {
                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    canseek = ChimneyMPDMediaElement.CanSeek;
}); 
}
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                canseek = false;
            }
#endif
            if (canseek)
            {
                if (e.arguments.Count > 0)
                {
                    int newpos = 0;

                    if (e.arguments[0].StartsWith("+"))
                    {
                        suc = int.TryParse(e.arguments[0].Remove(0, 1), out newpos);
                        if (suc)
                        {
#if WINDOWS_PHONE_APP
                            BackgroundMediaPlayer.Current.Position = BackgroundMediaPlayer.Current.Position + new TimeSpan(0, 0, newpos);
#else
                            try
                            {
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    ChimneyMPDMediaElement.Position = ChimneyMPDMediaElement.Position + new TimeSpan(0, 0, newpos);
}); 
}
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
#endif  
                         }
                    }
                    else if (e.arguments[0].StartsWith("-"))
                    {
                        suc = int.TryParse(e.arguments[0].Remove(0,1), out newpos);
                        if (suc)
                        {
#if WINDOWS_PHONE_APP
                            BackgroundMediaPlayer.Current.Position = BackgroundMediaPlayer.Current.Position - new TimeSpan(0, 0, newpos);
#else
                            try
                            {
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    ChimneyMPDMediaElement.Position = ChimneyMPDMediaElement.Position - new TimeSpan(0, 0, newpos);
}); 
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }

#endif
                        }
                    }
                    else
                    {
                        suc = int.TryParse(e.arguments[0], out newpos);
                        if(suc)
                        {
#if WINDOWS_PHONE_APP
                            BackgroundMediaPlayer.Current.Position = new TimeSpan(0, 0, newpos);
#else
                            try
                            {
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    ChimneyMPDMediaElement.Position = new TimeSpan(0, 0, newpos);
});
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine(ex.Message);
                            }
#endif
                        }
                    }
                }
            }


            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if(suc) if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("player"));
        }
 void chimneyMpdServer_OnStop(object sender, ResponseEventArgs e)
 {
     Stop();
     chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
     if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("player"));
 }
        async void chimneyMpdServer_OnToggleOutput(object sender, ResponseEventArgs e)
        {
            bool suc = false;
            int id = 0;

            if (e.arguments.Count > 0)
            {
                suc = int.TryParse(e.arguments[0], out id);
            }

            if (suc)
            {
                var audioOutput = await Dbconnection.FindAsync<AudioOutput>(o => o.AudioOutputId == id);

                if(audioOutput != null)
                {
                    audioOutput.Enabled = (audioOutput.Enabled) ? false : true;

                    await Dbconnection.UpdateAsync(audioOutput);
                }
            }


            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("outputs"));
        }
        async void chimneyMpdServer_OnPlay(object sender, ResponseEventArgs e)
        {
            int index = 0;
            if (e.arguments.Count > 0)
            {
                try
                {
                    index = Convert.ToInt32(e.arguments[0]);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

#if WINDOWS_PHONE_APP
            if (current_state.Equals("pause") && BackgroundMediaPlayer.Current.CurrentState == MediaPlayerState.Paused)
#else

            bool statetrue = false;
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
            statetrue = (ChimneyMPDMediaElement.CurrentState == MediaElementState.Paused) ? true : false;
});

            if (current_state.Equals("pause") && statetrue)
#endif
            {
                PlayOnPause();

                //if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("player"));
            }           
            else
            {
                CurrentPlaylist song = null;

                var currentPlaylist = await Dbconnection.QueryAsync<CurrentPlaylist>("SELECT * FROM CurrentPlaylist");

                if (currentPlaylist.Count > 0)
                {
                    if (option_random)
                    {
                        Random ran = new Random();
                        song = currentPlaylist[ran.Next(0, currentPlaylist.Count - 1)];
                    }
                    else if (currentPlaylist.Count > index)
                    {                      
                        song = currentPlaylist[index];
                    }

                    if (song != null)
                    {
                       Play(song.Uri, song.IsUri);
                    }

                    await Dbconnection.QueryAsync<CurrentPlaylist>("UPDATE CurrentPlaylist SET CurrentSong = 0 WHERE CurrentSong = 1");

                    song.CurrentSong = true;
                    await Dbconnection.UpdateAsync(song);
                }
            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("player"));

        }
        async void chimneyMpdServer_OnListPlaylistInfo(object sender, ResponseEventArgs e)
        {
            bool suc = false;

            string playlistName = string.Empty;

            string response = string.Empty;

            if (e.arguments.Count > 0)
            {
                playlistName = e.arguments[0];
            }

            var playlistToList = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName);

            if (playlistToList != null)
            {
                var playlistsItems = await Dbconnection.QueryAsync<PlaylistFile>("SELECT * FROM PlaylistFiles WHERE PlaylistId = " + playlistToList.PlaylistId + " ORDER BY Position");
                
                foreach(PlaylistFile playlistItem in playlistsItems)
                {
                    if(playlistItem.IsUri)
                    {
                        response += "file: " + playlistItem.Uri + "\n";
                        response += "Pos: " + playlistItem.Position + "\n";
                    }
                    else
                    {
                        var file = await Dbconnection.FindAsync<File>(o => o.FileId == playlistItem.FileId);

                        if(file != null)
                        {
                            response += file.ToResponseString();
                        }
                    }
                    
                }
            }

            chimneyMpdServer.AppendResponse(response, e.id, e.position);

        }
        async void chimneyMpdServer_OnOutputs(object sender, ResponseEventArgs e)
        {
            string response = string.Empty;
            var audioOutputs = await Dbconnection.QueryAsync<AudioOutput>("SELECT * FROM AudioOutputs");

            foreach (AudioOutput audioOutput in audioOutputs)
            {
                response += audioOutput.ToResponseString();
            }

            chimneyMpdServer.AppendResponse(response, e.id, e.position);
        }
        async void chimneyMpdServer_OnPlaylistAdd(object sender, ResponseEventArgs e)
        {
            bool suc = false;

            string playlistName = string.Empty;
            string uri = string.Empty;

            bool addasuri = false;

            if (e.arguments.Count > 1)
            {
                playlistName = e.arguments[0];
                uri = e.arguments[1];
            }

            var playlistToAddTo = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName);

            if (playlistToAddTo == null)
            {
                Playlist newStoredPlaylist = new Playlist()
                {
                    Name = playlistName,
                    LastModified = DateTime.Now.ToString("s")
                };

                await Dbconnection.InsertAsync(newStoredPlaylist);

                playlistToAddTo = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName);
            }

            var fileToAdd = await Dbconnection.FindAsync<File>(o => o.RelativePath == uri);

            if (fileToAdd == null) addasuri = true;

            if(playlistToAddTo != null)
            {
                PlaylistFile newPlaylistFile = new PlaylistFile() { 
                    FileId = (addasuri) ? -1 : fileToAdd.FileId,
                    IsUri = addasuri,
                    Uri = (addasuri) ? uri : fileToAdd.FilePath,
                    Position = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM PlaylistFiles WHERE PlaylistId = " + playlistToAddTo.PlaylistId),
                    PlaylistId = playlistToAddTo.PlaylistId
                };

                await Dbconnection.InsertAsync(newPlaylistFile);

                playlistToAddTo.LastModified = DateTime.Now.ToString("s");

                await Dbconnection.UpdateAsync(playlistToAddTo);

            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("stored_playlist"));
        }
        async void chimneyMpdServer_OnSetVol(object sender, ResponseEventArgs e)
        {
            if(e.arguments.Count > 0)
            {
                try
                {
                    double newvol = Convert.ToDouble(e.arguments[0]);

#if WINDOWS_PHONE_APP
                    BackgroundMediaPlayer.Current.Volume = newvol * 0.01;
#else
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    ChimneyMPDMediaElement.Volume = newvol * 0.01;
});
#endif
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
                if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("mixer"));

            }

        }
        async void chimneyMpdServer_OnPlaylistMove(object sender, ResponseEventArgs e)
        {
            bool suc = false;

            string playlistName = string.Empty;
            int fileId = 0;
            int position = 0;

            if (e.arguments.Count > 2)
            {
                playlistName = e.arguments[0];
                suc = int.TryParse(e.arguments[1], out fileId);
                suc = (suc) ? int.TryParse(e.arguments[2], out position) : false;
            }

            if (suc)
            {
                var playlistToMoveIn = await Dbconnection.FindAsync<Playlist>(o => o.Name == playlistName);

                if (playlistToMoveIn != null)
                {
                    int playlistid = playlistToMoveIn.PlaylistId;
                    var currentPlaylistFiles = await Dbconnection.QueryAsync<PlaylistFile>("SELECT * FROM PlaylistFiles WHERE PlaylistId = " + playlistid + " AND FileId = " + fileId + " AND IsUri = 0");

                    PlaylistFile playlistFile = (currentPlaylistFiles.Count > 0) ? currentPlaylistFiles[0] : null;

                    if (playlistFile != null)
                    {
                        if (position >= 0)
                        {
                            await Dbconnection.QueryAsync<CurrentPlaylist>("UPDATE PlaylistFiles SET Position=Position+1 WHERE PlaylistId " + playlistid + " Position >= " + position);
                            if (position > playlistFile.Position)
                            {
                                await Dbconnection.QueryAsync<CurrentPlaylist>("UPDATE PlaylistFiles SET Position=Position-1 WHERE PlaylistId " + playlistid + " Position > " + playlistFile.Position + " AND Position <= " + position);
                            }
                            playlistFile.Position = position;
                            await Dbconnection.UpdateAsync(playlistFile);

                            playlistToMoveIn.LastModified = DateTime.Now.ToString("s");

                            await Dbconnection.UpdateAsync(playlistToMoveIn);
                        }
                        else suc = false;
                        suc = true;
                    }
                }
                else suc = false;
            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);

            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("stored_playlist"));
        }
        async void chimneyMpdServer_OnStats(object sender, ResponseEventArgs e)
        {
            string response = string.Empty;

            response += "artists: " + await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM Artists") + "\n";

            response += "albums: " + await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM Albums") + "\n";

            int files = await Dbconnection.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM Files");

            response += "songs: " + files + "\n";

            response += "uptime: " + DateTime.Now.Subtract(ServerStatedTime).Seconds + "\n";

            response += (files > 0) ? "db_playtime: " + await Dbconnection.ExecuteScalarAsync<int>("SELECT SUM(Time) FROM Files") + "\n" : "db_playtime: 0\n";

            TimeSpan span = db_last_update.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            response += "db_update: " + span.TotalSeconds + "\n";

            try
            {

#if WINDOWS_PHONE_APP
            response += "playtime: " + (ServerPlaytime + BackgroundMediaPlayer.Current.Position.TotalSeconds) + "\n";
#else
                             await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                response += "playtime: " + (ServerPlaytime + ChimneyMPDMediaElement.Position.TotalSeconds) + "\n";
                });
#endif
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                response += "playtime: 0\n";
            }

            chimneyMpdServer.AppendResponse(response, e.id, e.position);
        }
        async void chimneyMpdServer_OnRm(object sender, ResponseEventArgs e)
        {
            if (e.arguments.Count > 0)
            {
                string rmplaylistname = e.arguments[0];

                var rmPlaylists = await Dbconnection.FindAsync<Playlist>(o => o.Name == rmplaylistname);

                if (rmPlaylists != null)
                {
                    await Dbconnection.QueryAsync<PlaylistFile>("DELETE FROM PlaylistFiles WHERE PlaylistId = " + rmPlaylists.PlaylistId);
                    
                    await Dbconnection.DeleteAsync(rmPlaylists);
                }
            }

            chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
            if (OnIdleEvent != null) OnIdleEvent(this, new IdleEventArgs("stored_playlist"));

        }
        async void chimneyMpdServer_OnPlChanges(object sender, ResponseEventArgs e)
        {
            if (e.arguments.Count > 0)
            {
                int b = -1;
                try
                {
                   b  = Convert.ToInt32(e.arguments.First<string>());
                }
                catch
                {
                    b = -1;
                }

                if (b == -1) chimneyMpdServer.AppendResponse(string.Empty, e.id, e.position);
                else
                {
                    var currentPlaylist = await Dbconnection.QueryAsync<CurrentPlaylist>("SELECT * FROM CurrentPlaylist WHERE Version > " + b + " ORDER BY PositionId");

                    string response = string.Empty;

                    foreach (CurrentPlaylist cp in currentPlaylist)
                    {
                        //var files = await Dbconnection.QueryAsync<File>("SELECT * FROM Files WHERE FileId = " + cp.FileId);
                        if (cp.IsUri)
                        {
                            response += "file: " + cp.Uri + "\n";
                            response += "Pos: " + cp.PositionId + "\n";
                        }
                        else
                        {
                            var file = await Dbconnection.FindAsync<File>(o => o.FileId == cp.FileId);
                            if (file != null)
                            {
                                file.Pos = cp.PositionId;
                                await Dbconnection.UpdateAsync(file);

                                response += file.ToResponseString();
                            }
                        }
                    }

                    chimneyMpdServer.AppendResponse(response, e.id, e.position);
                }
            }

        }