--[[
Copyright (c) 2011-2012 qeeplay.com
http://dualface.github.com/quick-cocos2d-x/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
--[[--
Convert to number.
@param mixed v
@return number
]]
function tonum(v, default)
    default = default or 0
    return tonumber(v) or default
end
--[[--
Convert to integer.
@param mixed v
@return number(integer)
]]
function toint(v)
    return math.round(tonumber(v))
end
--[[--
Convert to boolean.
@param mixed v
@return boolean
]]
function tobool(v)
    return (v ~= nil and v ~= false)
end
--[[--
Convert to table.
@param mixed v
@return table
]]
function totable(v)
    if type(v) ~= "table" then v = {} end
    return v
end
--[[--
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). string.format() alias.
@param string format
@param mixed ...
@return string
]]
function format(...)
    return string.format(...)
end
--[[--
Creating a copy of an table with fully replicated properties.
**Usage:**
    -- Creating a reference of an table:
    local t1 = {a = 1, b = 2}
    local t2 = t1
    t2.b = 3    -- t1 = {a = 1, b = 3} <-- t1.b changed
    -- Createing a copy of an table:
    local t1 = {a = 1, b = 2}
    local t2 = clone(t1)
    t2.b = 3    -- t1 = {a = 1, b = 2} <-- t1.b no change
@param mixed object
@return mixed
]]
function clone(object)
    local lookup_table = {}
    local function _copy(object)
        if type(object) ~= "table" then
            return object
        elseif lookup_table[object] then
            return lookup_table[object]
        end
        local new_table = {}
        lookup_table[object] = new_table
        for key, value in pairs(object) do
            new_table[_copy(key)] = _copy(value)
        end
        return setmetatable(new_table, getmetatable(object))
    end
    return _copy(object)
end
--[[--
Create an class.
**Usage:**
    local Shape = class("Shape")
    -- base class
    function Shape:ctor(shapeName)
        self.shapeName = shapeName
        printf("Shape:ctor(%s)", self.shapeName)
    end
    function Shape:draw()
        printf("draw %s", self.shapeName)
    end
    --
    local Circle = class("Circle", Shape)
    function Circle:ctor()
        Circle.super.ctor(self, "circle")   -- call super-class method
        self.radius = 100
    end
    function Circle:setRadius(radius)
        self.radius = radius
    end
    function Circle:draw()                  -- overrideing super-class method
        printf("draw %s, raidus = %0.2f", self.shapeName, self.raidus)
    end
    --
    local Rectangle = class("Rectangle", Shape)
    function Rectangle:ctor()
        Rectangle.super.ctor(self, "rectangle")
    end
    --
    local circle = Circle.new()             -- output: Shape:ctor(circle)
    circle:setRaidus(200)
    circle:draw()                           -- output: draw circle, radius = 200.00
    local rectangle = Rectangle.new()       -- output: Shape:ctor(rectangle)
    rectangle:draw()                        -- output: draw rectangle
@param string classname
@param table|function super-class
@return table
]]
function class(classname, super)
    local superType = type(super)
    local cls
    if superType ~= "function" and superType ~= "table" then
        superType = nil
        super = nil
    end
    if superType == "function" or (super and super.__ctype == 1) then
        -- inherited from native C++ Object
        cls = {}
        if superType == "table" then
            -- copy fields from super
            for k,v in pairs(super) do cls[k] = v end
            cls.__create = super.__create
            cls.super    = super
        else
            cls.__create = super
            cls.ctor = function() end
        end
        cls.__cname = classname
        cls.__ctype = 1
        function cls.new(...)
            local instance = cls.__create(...)
            -- copy fields from class to native object
            for k,v in pairs(cls) do instance[k] = v end
            instance.class = cls
            instance:ctor(...)
            return instance
        end
    else
        -- inherited from Lua Object
        if super then
            cls = clone(super)
            cls.super = super
        else
            cls = {ctor = function() end}
        end
        cls.__cname = classname
        cls.__ctype = 2 -- lua
        cls.__index = cls
        function cls.new(...)
            local instance = setmetatable({}, cls)
            instance.class = cls
            instance:ctor(...)
            return instance
        end
    end
    return cls
end
--[[--
]]
function import(moduleName, currentModuleName)
    local currentModuleNameParts
    local moduleFullName = moduleName
    local offset = 1
    while true do
        if string.byte(moduleName, offset) ~= 46 then -- .
            moduleFullName = string.sub(moduleName, offset)
            if currentModuleNameParts and #currentModuleNameParts > 0 then
                moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName
            end
            break
        end
        offset = offset + 1
        if not currentModuleNameParts then
            if not currentModuleName then
                local n,v = debug.getlocal(3, 1)
                currentModuleName = v
            end
            currentModuleNameParts = string.split(currentModuleName, ".")
        end
        table.remove(currentModuleNameParts, #currentModuleNameParts)
    end
    return require(moduleFullName)
end
--[[--
]]
function handler(target, method)
    return function(...) return method(target, ...) end
end
--[[--
]]
function handlerObject(object)
    return function(event, ...)
        if object[event] then
            return object[event](object, ...)
        end
    end
end
--[[--
Returns a associative table containing the matching values.
@param table arr
@param table names
@return array
]]
function export(arr, names)
    local args = {}
    for k, def in pairs(names) do
        if type(k) == "number" then
            args[def] = arr[def]
        else
            args[k] = arr[k] or def
        end
    end
    return args
end
--[[--
hecks if the given key or index exists in the table.
@param table arr
@param mixed key
@return boolean
]]
function isset(arr, key)
    return type(arr) == "table" and arr[key] ~= nil
end
--[[--
Rounds a float.
@param number num
@return number(integer)
]]
function math.round(num)
    return math.floor(num + 0.5)
end
--[[--
Checks whether a file exists.
@param string path
@return boolean
]]
function io.exists(path)
    local file = io.open(path, "r")
    if file then
        io.close(file)
        return true
    end
    return false
end
--[[--
Reads entire file into a string, or return FALSE on failure.
@param string path
@return string
]]
function io.readfile(path)
    local file = io.open(path, "r")
    if file then
        local content = file:read("*a")
        io.close(file)
        return content
    end
    return nil
end
--[[--
Write a string to a file, or return FALSE on failure.
@param string path
@param string content
@param string mode
@return boolean
### Note:
The mode string can be any of the following:
    "r": read mode
    "w": write mode;
    "a": append mode;
    "r+": update mode, all previous data is preserved;
    "w+": update mode, all previous data is erased; (the default);
    "a+": append update mode, previous data is preserved, writing is only allowed at the end of file.
]]
function io.writefile(path, content, mode)
    mode = mode or "w+"
    local file = io.open(path, mode)
    if file then
        if file:write(content) == nil then return false end
        io.close(file)
        return true
    else
        return false
    end
end
--[[--
Returns information about a file path.
**Usage:**
    local path = "/var/app/test/abc.png"
    local pathinfo  = io.pathinfo(path)
    -- pathinfo.dirname  = "/var/app/test/"
    -- pathinfo.filename = "abc.png"
    -- pathinfo.basename = "abc"
    -- pathinfo.extname  = ".png"
@param string path
@return table
]]
function io.pathinfo(path)
    local pos = string.len(path)
    local extpos = pos + 1
    while pos > 0 do
        local b = string.byte(path, pos)
        if b == 46 then -- 46 = char "."
            extpos = pos
        elseif b == 47 then -- 47 = char "/"
            break
        end
        pos = pos - 1
    end
    local dirname = string.sub(path, 1, pos)
    local filename = string.sub(path, pos + 1)
    extpos = extpos - pos
    local basename = string.sub(filename, 1, extpos - 1)
    local extname = string.sub(filename, extpos)
    return {
        dirname = dirname,
        filename = filename,
        basename = basename,
        extname = extname
    }
end
--[[--
Gets file size, or return FALSE on failure.
@param string path
@return number(integer)
]]
function io.filesize(path)
    local size = false
    local file = io.open(path, "r")
    if file then
        local current = file:seek()
        size = file:seek("end")
        file:seek("set", current)
        io.close(file)
    end
    return size
end
--[[--
Count all elements in an table.
@param table t
@return number(integer)
]]
function table.nums(t)
    local count = 0
    for k, v in pairs(t) do
        count = count + 1
    end
    return count
end
--[[--
Return all the keys or a subset of the keys of an table.
**Usage:**
    local t = {a = 1, b = 2, c = 3}
    local keys = table.keys(t)
    -- keys = {"a", "b", "c"}
@param table t
@return table
]]
function table.keys(t)
    local keys = {}
    for k, v in pairs(t) do
        keys[#keys + 1] = k
    end
    return keys
end
--[[--
Return all the values of an table.
**Usage:**
    local t = {a = "1", b = "2", c = "3"}
    local values = table.values(t)
    -- values = {1, 2, 3}
@param table t
@return table
]]
function table.values(t)
    local values = {}
    for k, v in pairs(t) do
        values[#values + 1] = v
    end
    return values
end
--[[--
Merge tables.
**Usage:**
    local dest = {a = 1, b = 2}
    local src  = {c = 3, d = 4}
    table.merge(dest, src)
    -- dest = {a = 1, b = 2, c = 3, d = 4}
@param table dest
@param table src
]]
function table.merge(dest, src)
    for k, v in pairs(src) do
        dest[k] = v
    end
end
--[[--
insert list.
**Usage:**
    local dest = {1, 2, 3}
    local src  = {4, 5, 6}
    table.insertTo(dest, src)
    -- dest = {1, 2, 3, 4, 5, 6}
    dest = {1, 2, 3}
    table.insertTo(dest, src, 5)
    -- dest = {1, 2, 3, nil, 4, 5, 6}
@param table dest
@param table src
@param table begin insert position for dest
]]
function table.insertTo(dest, src, begin)
    begin = tonumber(begin)
    if begin == nil then
        begin = #dest + 1
    end
    local len = #src
    for i = 0, len - 1 do
        dest[i + begin] = src[i + 1]
    end
end
function table.maxkey(tb)
    local max = 0
    for k, v in pairs(tb) do
        if k > max then
            max = k
        end
    end
    return max
end
function table.minkey(tb)
    local min = math.huge
    for k, v in pairs(tb) do
        if k < min then
            min = k
        end
    end
    return min
end
--[[--
Convert special characters to HTML entities.
The translations performed are:
-   '&' (ampersand) becomes '&'
-   '"' (double quote) becomes '"'
-   "'" (single quote) becomes '''
-   '<' (less than) becomes '<'
-   '>' (greater than) becomes '>'
@param string input
@return string
]]
function string.htmlspecialchars(input)
    for k, v in pairs(string._htmlspecialchars_set) do
        input = string.gsub(input, k, v)
    end
    return input
end
string._htmlspecialchars_set = {}
string._htmlspecialchars_set["&"] = "&"
string._htmlspecialchars_set["\""] = """
string._htmlspecialchars_set["'"] = "'"
string._htmlspecialchars_set["<"] = "<"
string._htmlspecialchars_set[">"] = ">"
--[[--
Inserts HTML line breaks before all newlines in a string.
Returns string with '
' inserted before all newlines (\n).
@param string input
@return string
]]
function string.nl2br(input)
    return string.gsub(input, "\n", "
")
end
--[[--
Returns a HTML entities formatted version of string.
@param string input
@return string
]]
function string.text2html(input)
    input = string.gsub(input, "\t", "    ")
    input = string.htmlspecialchars(input)
    input = string.gsub(input, " ", " ")
    input = string.nl2br(input)
    return input
end
--[[--
Split a string by string.
@param string str
@param string delimiter
@return table
]]
function string.split(str, delimiter)
    if (delimiter=='') then return false end
    local pos,arr = 0, {}
    -- for each divider found
    for st,sp in function() return string.find(str, delimiter, pos, true) end do
        table.insert(arr, string.sub(str, pos, st - 1))
        pos = sp + 1
    end
    table.insert(arr, string.sub(str, pos))
    return arr
end
--[[--
Strip whitespace (or other characters) from the beginning of a string.
@param string str
@return string
]]
function string.ltrim(str)
    return string.gsub(str, "^[ \t\n\r]+", "")
end
--[[--
Strip whitespace (or other characters) from the end of a string.
@param string str
@return string
]]
function string.rtrim(str)
    return string.gsub(str, "[ \t\n\r]+$", "")
end
--[[--
Strip whitespace (or other characters) from the beginning and end of a string.
@param string str
@return string
]]
function string.trim(str)
    str = string.gsub(str, "^[ \t\n\r]+", "")
    return string.gsub(str, "[ \t\n\r]+$", "")
end
--[[--
Make a string's first character uppercase.
@param string str
@return string
]]
function string.ucfirst(str)
    return string.upper(string.sub(str, 1, 1)) .. string.sub(str, 2)
end
--[[--
@param string str
@return string
]]
function string.urlencodeChar(char)
    return "%" .. string.format("%02X", string.byte(c))
end
--[[--
URL-encodes string.
@param string str
@return string
]]
function string.urlencode(str)
    -- convert line endings
    str = string.gsub(tostring(str), "\n", "\r\n")
    -- escape all characters but alphanumeric, '.' and '-'
    str = string.gsub(str, "([^%w%.%- ])", string.urlencodeChar)
    -- convert spaces to "+" symbols
    return string.gsub(str, " ", "+")
end
--[[--
Get UTF8 string length.
@param string str
@return int
]]
function string.utf8len(str)
    local len  = #str
    local left = len
    local cnt  = 0
    local arr  = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
    while left ~= 0 do
        local tmp = string.byte(str, -left)
        local i   = #arr
        while arr[i] do
            if tmp >= arr[i] then
                left = left - i
                break
            end
            i = i - 1
        end
        cnt = cnt + 1
    end
    return cnt
end
--[[--
Return formatted string with a comma (",") between every group of thousands.
**Usage:**
    local value = math.comma("232423.234") -- value = "232,423.234"
@param number num
@return string
]]
function string.formatNumberThousands(num)
    local formatted = tostring(tonumber(num))
    while true do
        formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
        if k == 0 then break end
    end
    return formatted
end
function table.find(t, item)
    return table.keyOfItem(t, item) ~= nil
end
function table.keyOfItem(t, item)
    for k,v in pairs(t) do
        if v == item then return k end
    end
    return nil
end
function table.removeItem(list, item, removeAll)
    local rmCount = 0
    for i = 1, #list do
        if list[i - rmCount] == item then
            table.remove(list, i - rmCount)
            if removeAll then
                rmCount = rmCount + 1
            else
                break
            end
        end
    end
end
function table.array2Table(arr)
    local ret = {}
    for i=1, #arr, 2 do
        ret[arr[i]] = arr[i+1]
    end
    return ret
end