/*******************************************************************************

    
    Cloud Firewall - a browser extension/addon that allows users to block connections 
    to sites, pages and web resources (images, videos, etc) hosted in major cloud services
    if the user wishes to do so.
    Copyright (C) 2019 Niklas Poslovski
    Copyright (C) 2019 Gokulakrishna Sudharsan

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Home: https://notabug.org/nipos/cloud-firewall

    This file is taken from https://github.com/danielcompton/ip-range-check and
    modified to work in the browser instead of NodeJS
*/
 check_many_cidrs = (parsed_addr, kind, range) => {
    if (typeof (range) === "string") {
        return check_single_cidr(parsed_addr, kind, range)
    }
    else if (typeof (range) === "object") //list
    {
        var ip_is_in_range = false;
        for (var i = 0; i < range.length; i++) {
            if (check_single_cidr(parsed_addr, kind, range[i])) {
                ip_is_in_range = true;
                break
            }
        }
        return ip_is_in_range;
    }
}

 check_single_cidr = (parsed_addr, kind, cidr) => {
    try {
        if (cidr.indexOf('/') === -1) {
            var parsed_cidr_as_ip = ipaddr.process(cidr);
            if ((kind === "ipv6") && (parsed_cidr_as_ip.kind() === "ipv6")){
                return (parsed_addr.toNormalizedString() === parsed_cidr_as_ip.toNormalizedString())
            }
            return (parsed_addr.toString() == parsed_cidr_as_ip.toString())
        }
        else {
            var parsed_range = ipaddr.parseCIDR(cidr);
            return parsed_addr.match(parsed_range)
        }
    }
    catch (e) {
        return false
    }
}
