package com.dougmccune.muxmaster.api
{
    import flash.events.Event;
    
    import mx.rpc.events.ResultEvent;
    import mx.rpc.http.HTTPService;
    
    [Event(name="complete", type="flash.events.Event")]
    
    public class MuxListing
    {
        namespace ns = "http://www.w3.org/1999/xhtml";
        
        [Bindable] public var playlists:Array;
        
        private var numToLoad:int;
        
        public function loadRandom(number:int=10):void {
            numToLoad = number;
            
            var service:HTTPService = new HTTPService();
            service.url = "http://muxtape.com/";
            service.resultFormat = HTTPService.RESULT_FORMAT_E4X;
            service.addEventListener(ResultEvent.RESULT, resultHandler);
            
            service.send();
        }
        
        public function loadRelated(playlist:MuxPlaylist):void {
            playlists = new Array(playlist.user).concat(playlist.relatedUsers.slice(-10));
            dispatchEvent(new Event(Event.COMPLETE));
        }
        
        private function resultHandler(event:ResultEvent):void {
            use namespace ns;
            
            var playlists:XMLList = XML(event.result).body.div.div.ul.li.a;
            
            var array:Array = [];
            
            for each(var user:XML in playlists) {
                array.push(user.toString());
                
                if(array.length == numToLoad) break;
            }
            
            this.playlists = array;
            
            dispatchEvent(new Event(Event.COMPLETE));
        }
    }
}