var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { jsx as _jsx } from "react/jsx-runtime";
import { store } from 'src/app/redux/store';
import { googleLocationApi } from './constants';
export var postalCodeUSRegex = new RegExp('^[0-9]{5}(-[0-9]{4})?$');
export var postalCodeBMRegex = new RegExp('^[a-zA-Z]{2}s[0-9]{2}?$');
export var postalCodeVIRegex = new RegExp('^008(([0-4]\\d)|(5[01]))([ \\-]\\d{4})?$');
export var postalCodePRRegex = new RegExp('^[0]{2}[0-9]{3}?$');
export var postalCodeCARegex = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] \d[ABCEGHJ-NPRSTV-Z]\d$/i;
export var postalCodeBRRegex = new RegExp('^[0-9]{5}[-][0-9]{3}$|^[0-9]{5}$|^[0-9]{8}$');
export var postalCodeCLRegex = new RegExp('^[0-9]{7}$');
export var postalCode5digit = new RegExp('^[0-9]{5}$');
export var distUnitMap = { mile: 3956, km: 6371 };
export var daysOfWeek = [
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
    'Sunday',
];
export var yearInMs = 31557600000;
export var getHostEnv = function (testHostnames) {
    var isProdBuild = process.env.NODE_ENV === 'production';
    var host = window.location.hostname;
    var testHosts = testHostnames || [process.env.REACT_APP_TEST_HOST];
    var isTest = testHosts.includes(host);
    if (isProdBuild)
        return isTest ? 'test' : 'production';
    return 'dev';
};
export var makePath = function (path) {
    return path.charAt(0) === '/' ? path : "/".concat(path);
};
export var wait = function (ms) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
    switch (_a.label) {
        case 0: return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(function () { return resolve(); }, ms); })];
        case 1: return [2 /*return*/, _a.sent()];
    }
}); }); };
export var waitUntil = function (checkCondition, callback, waitInMs) { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, wait(waitInMs)];
            case 1:
                _a.sent();
                if (!checkCondition()) return [3 /*break*/, 3];
                return [4 /*yield*/, waitUntil(checkCondition, callback, waitInMs)];
            case 2:
                _a.sent();
                return [3 /*break*/, 4];
            case 3:
                callback();
                _a.label = 4;
            case 4: return [2 /*return*/];
        }
    });
}); };
export var setCookie = function (name, value, days, path, domain, secure) {
    var expires = 'Mon, 01-Jan-2038 12:00:00 GMT';
    if (days != null && days > 0) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        expires = date.toUTCString();
    }
    // should pass days as 0 for session cookie
    if (days === 0)
        expires = '';
    document.cookie =
        name +
            '=' +
            escape(value) +
            (expires ? ';expires=' + expires : '') +
            (path ? ';path=' + path : '') +
            (domain ? ';domain=' + domain : '') +
            (secure ? ';secure' : '');
};
export var getCookie = function (name) {
    var nameLenPlus = name.length + 1;
    return (document.cookie
        .split(';')
        .map(function (c) { return c.trim(); })
        .filter(function (cookie) {
        return cookie.substring(0, nameLenPlus) === "".concat(name, "=");
    })
        .map(function (cookie) {
        return decodeURIComponent(cookie.substring(nameLenPlus));
    })[0] || null);
};
export var generateShortGuid = function () {
    return generateRandom('xxxxxxxxxxxx');
};
export var generateRandom = function (pattern) {
    return pattern.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
};
export var cheapRound = function (num, decLength) {
    var string = num.toString();
    if (!string.includes('.'))
        return num;
    var int = string.split('.')[0];
    var fraction = string.split('.')[1];
    return Number("".concat(int, ".").concat(fraction === null || fraction === void 0 ? void 0 : fraction.slice(0, decLength)));
};
export var splitToChunks = function (array, chunkSize) {
    if (!array.length)
        return [];
    var arrayOfArrays = [];
    for (var i = 0; i < array.length; i += chunkSize) {
        var chunk = array.slice(i, i + chunkSize);
        arrayOfArrays.push(chunk);
    }
    return arrayOfArrays;
};
export var isObject = function (item) {
    return item && typeof item === 'object' && !Array.isArray(item);
};
export var isEmptyObject = function (obj) {
    return JSON.stringify(obj) === '{}';
};
export var mergeDeep = function (target) {
    var _a, _b;
    var sources = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        sources[_i - 1] = arguments[_i];
    }
    if (!sources.length)
        return target;
    var source = sources.shift();
    if (target && source) {
        for (var key in source) {
            if (isObject(source[key])) {
                if (!target[key])
                    Object.assign(target, (_a = {}, _a[key] = {}, _a));
                mergeDeep(target[key], source[key]);
            }
            else {
                Object.assign(target, (_b = {}, _b[key] = source[key], _b));
            }
        }
    }
    return mergeDeep.apply(void 0, __spreadArray([target], __read(sources), false));
};
export var isEqual = function (a, b) {
    var aLength = Object.keys(a).length;
    var bLength = Object.keys(b).length;
    if (aLength !== bLength)
        return false;
    var isInvalidA = a == null || aLength < 1;
    var isInvalidB = b == null || bLength < 1;
    if (isInvalidA && !isInvalidB)
        return false;
    if (!isInvalidA && isInvalidB)
        return false;
    return !Object.entries(a).some(function (entry) {
        var key = entry[0];
        var value = entry[1];
        return value !== b[key];
    });
};
export var isEqualArrays = function (a, b) {
    var isInvalidA = a == null || a.length < 1;
    var isInvalidB = b == null || b.length < 1;
    if (isInvalidA && !isInvalidB)
        return false;
    if (!isInvalidA && isInvalidB)
        return false;
    if (a.length !== b.length)
        return false;
    return !a.some(function (rec, i) {
        var entry = Object.entries(rec);
        var key = entry[0][0];
        var value = entry[0][1];
        return value !== b[i][key];
    });
};
export var msToMinsAndSecs = function (millis, divider) {
    if (divider === void 0) { divider = '.'; }
    var minutes = Math.floor(millis / 60000);
    var seconds = Number(((millis % 60000) / 1000).toFixed(0));
    return minutes + divider + (seconds < 10 ? '0' : '') + seconds;
};
export var getTimeFormatted = function (date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    var ms = date.getMilliseconds();
    var hrs = String(hours).length === 1 ? String("0".concat(hours)) : hours;
    var mins = String(minutes).length === 1 ? String("0".concat(minutes)) : minutes;
    var secs = String(seconds).length === 1 ? String("0".concat(seconds)) : seconds;
    return "".concat(hrs, ":").concat(mins, ":").concat(secs, ":").concat(ms);
};
export var getTimeObj = function (date) {
    var timeData = date.split(':');
    var hours = Number(timeData[0]);
    var minutes = Number(timeData[1]);
    var seconds = Number(timeData[2]);
    var ms = Number(timeData[3]);
    return {
        hours: hours,
        minutes: minutes,
        seconds: seconds,
        ms: ms,
    };
};
export var isValidZip = function (zip, isCa, zipUtil) {
    if (isCa === void 0) { isCa = false; }
    var view = store.getState().common.view;
    var address = store.getState().filter.filters.address;
    if (store.getState().config.config.enableGoogleSearch)
        return address.length || zip ? true : false;
    if (!zip)
        return false;
    var zipUtility = zipUtil || store.getState().config.config.zipUtility;
    var getValidLength = function () {
        var mask = zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.mask;
        if (isCa)
            return postalCodeCARegex.test(zip);
        else {
            if (zipUtility.validLengths)
                return zipUtility.validLengths;
            if (mask)
                return [mask.replace(/[\WD_]/g, '').length];
            if (zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.maxLength)
                return [zipUtility.maxLength];
        }
        return false;
    };
    var validLength = getValidLength();
    if (typeof validLength === 'boolean')
        return validLength;
    return validLength
        ? validLength.some(function (v) { return zip.replace(/[\WD_]/g, '').trim().length === v; })
        : true;
};
export var canadaZipValidator = function (input, currentValue) {
    var _a, _b, _c, _d, _e, _f;
    if (!input)
        return '';
    if (input.length < currentValue.length) {
        return input;
    }
    if (/^[A-Z]$/i.test((_a = input[0]) !== null && _a !== void 0 ? _a : '') && input.length === 1)
        return input;
    if (/^\d$/.test((_b = input[1]) !== null && _b !== void 0 ? _b : '') && input.length === 2)
        return input;
    if (/^[A-Z]$/i.test((_c = input[2]) !== null && _c !== void 0 ? _c : '') && input.length === 3)
        return input + ' ';
    if (/^\d$/.test((_d = input[4]) !== null && _d !== void 0 ? _d : '') && input.length === 5)
        return input;
    if (/^[A-Z]$/i.test((_e = input[5]) !== null && _e !== void 0 ? _e : '') && input.length === 6)
        return input;
    if (/^\d$/.test((_f = input[6]) !== null && _f !== void 0 ? _f : '') && input.length === 7)
        return input;
    return false;
};
export var loadClientScript = function (src_1) {
    var args_1 = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args_1[_i - 1] = arguments[_i];
    }
    return __awaiter(void 0, __spreadArray([src_1], __read(args_1), false), void 0, function (src, timeout) {
        if (timeout === void 0) { timeout = 10000; }
        return __generator(this, function (_a) {
            return [2 /*return*/, new Promise(function (resolve, reject) {
                    var resolved = false;
                    var resv = function (error) {
                        if (!resolved) {
                            resolved = true;
                            if (error)
                                reject(new Error(error));
                            else
                                resolve();
                        }
                    };
                    window.setTimeout(function () { return resv('timeout'); }, timeout);
                    var script = document.createElement('script');
                    script.onload = function () {
                        resv('');
                    };
                    script.onerror = function (e) {
                        resv("error loading script: ".concat(e));
                    };
                    script.src = src;
                    document.body.append(script);
                })];
        });
    });
};
export var initGoogleAutoCompleteBackup = function (elementId, localeId, callback) { return __awaiter(void 0, void 0, void 0, function () {
    var localeSplit, GoogleMapSrc, opts, element, autocomplete;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                if (!!(typeof window.google === 'object' &&
                    typeof window.google.maps === 'object' &&
                    typeof window.google.maps.places === 'object')) return [3 /*break*/, 2];
                localeSplit = localeId.split('-');
                GoogleMapSrc = "".concat(googleLocationApi, "?libraries=geometry,places&key=").concat(process.env.REACT_APP_GOOGLE_KEY, "&language=").concat(localeSplit[0] || "en", "&region=").concat(localeSplit.splice(-1)[0] || 'US');
                return [4 /*yield*/, loadClientScript(GoogleMapSrc)];
            case 1:
                _a.sent();
                _a.label = 2;
            case 2:
                opts = {
                    types: ['geocode'],
                    componentRestrictions: { country: ["".concat(localeId === null || localeId === void 0 ? void 0 : localeId.split('-')[1])] },
                };
                element = Array.from(document.getElementsByTagName('input')).find(function (e) { return e.id === elementId; });
                if (typeof window.google !== 'object' || typeof window.google.maps !== 'object' || !element) {
                    console.log('Google not found');
                    return [2 /*return*/];
                }
                autocomplete = new window.google.maps.places.Autocomplete(element, opts);
                window.google.maps.event.addListener(autocomplete, 'place_changed', function () {
                    try {
                        var place = autocomplete.getPlace();
                        var formatted_address = place.formatted_address, geometry = place.geometry;
                        if (!geometry || !geometry.location) {
                            console.log("No details available for input: '" + place.name + "'");
                            return;
                        }
                        callback({ geometry: geometry, formatted_address: formatted_address });
                    }
                    catch (x) {
                        console.log(x);
                    }
                });
                return [2 /*return*/];
        }
    });
}); };
export var HfdLogo = function (_a) {
    var color = _a.color, width = _a.width;
    var url = color === 'white'
        ? 'https://images.ctfassets.net/vh25xg5i1h5l/2LZCBwbjdB748bn78gxhti/b8b258d66afa8f986c2b8bcea3adf29f/icon-hfd-ffffff.png'
        : 'https://images.ctfassets.net/vh25xg5i1h5l/1R3CWgP10VNhVGy1EBuNBt/968055cfe7b118afe9f2479e36d72c0e/output-onlinepngtools.png';
    return _jsx("img", { width: width || '24px', src: url, alt: "HFD Icon" });
};
