require 'json'

require 'httparty'

require 'yaml'

class Main

class Item

attr_accessor :icon , :id , :type , :name , :current_trend , :price , :month_trend , :month_fluctuation ,

:three_month_trend , :three_month_fluctuation , :six_month_trend , :six_month_fluctuation ,

:today_trend , :today_fluctuation , :daily_graph , :average_graph , :exists

def getTrend ( trend )

trend. sub ( 'neutral' , '↕' ) . sub ( 'positive' , '↑' ) . sub ( 'negative' , '↓' )

end

def queryItem ( item_id )

begin

JSON. parse ( HTTParty. get ( 'http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=' + item_id ) )

rescue StandardError

false

end

end

def queryGraph ( item_id )

begin

JSON. parse ( HTTParty. get ( 'http://services.runescape.com/m=itemdb_rs/api/graph/X.json' . sub ( 'X' , item_id ) ) )

rescue StandardError

false

end

end

def initialize ( item_code )

item_json = queryItem ( item_code )

graph_json = queryGraph ( item_code )

self . exists = false

if item_json != false && graph_json != false

self . exists = true

self . daily_graph = Hash . new

self . average_graph = Hash . new

self . icon = item_json [ 'item' ] [ 'icon_large' ]

self . id = item_json [ 'item' ] [ 'id' ]

self . type = item_json [ 'item' ] [ 'type' ]

self . name = item_json [ 'item' ] [ 'name' ]

self . current_trend = getTrend ( item_json [ 'item' ] [ 'current' ] [ 'trend' ] )

self . price = item_json [ 'item' ] [ 'current' ] [ 'price' ]

self . today_trend = getTrend ( item_json [ 'item' ] [ 'today' ] [ 'trend' ] )

self . today_fluctuation = item_json [ 'item' ] [ 'today' ] [ 'price' ]

self . month_trend = getTrend ( item_json [ 'item' ] [ 'day30' ] [ 'trend' ] )

self . month_fluctuation = item_json [ 'item' ] [ 'day30' ] [ 'change' ]

self . three_month_trend = getTrend ( item_json [ 'item' ] [ 'day90' ] [ 'trend' ] )

self . three_month_fluctuation = item_json [ 'item' ] [ 'day90' ] [ 'change' ]

self . six_month_trend = getTrend ( item_json [ 'item' ] [ 'day180' ] [ 'trend' ] )

self . six_month_fluctuation = item_json [ 'item' ] [ 'day180' ] [ 'change' ]

graph_json [ 'daily' ] . each do | key, value |

date = Date . strptime ( ( key. to_f / 1000 ) . to_s , '%s' )

self . daily_graph [ date. to_s ] = value

end

graph_json [ 'average' ] . each do | key, value |

date = Date . strptime ( ( key. to_f / 1000 ) . to_s , '%s' )

self . average_graph [ date. to_s ] = value

end

end

end

end

puts Dir . pwd

( 1 .. 50000 ) . each do | n |

puts 'Querying for item ' + n. to_s

item = Item. new ( n. to_s )

if item. exists

File . open ( Dir . pwd + '/items/' + n. to_s + '.yml' , 'w' ) { | f | f. write ( YAML ::dump ( item ) ) }

puts 'Item ' + n. to_s + ' exists as ' + item. name + ', written serialized item object to ' + Dir . pwd + '/items/' + n. to_s + '.yml'

sleep ( 6 )

else

puts 'Item ' + n. to_s + ' does not exist.'

sleep ( 6 )

end

end