import { get, writable } from "svelte/store"
import { location } from "./store"
import { spaNavigate } from "./actions"
import { get as _get } from "lodash"

import Cryptcha from "cryptcha"
import { cryptchaSiteId } from "../../../api/hooks/config-client"

type filterMap = { [key: string]: string[] }
type keyMapping = { [key: string]: string }

export function applyFilterFromHash(
    hash: string,
    keys: keyMapping,
    items: any[],
    callback?: () => void
): { filteredItems: any[]; newFilter?: filterMap } {
    let filteredItems: any[] = []

    if (items?.length && hash) {
        const hashParts = hash.replace(/^#/, "").split("&")
        const newFilter: { [key: string]: string[] } = {}
        Object.keys(keys).forEach((key) => {
            newFilter[key] = []
        })
        let doFiltering = false
        hashParts.forEach((part) => {
            const [key, value] = part.split("=")
            if (key in newFilter) {
                newFilter[key] = value.split(",")
                if (newFilter[key].length) {
                    doFiltering = true
                }
            }
        })

        if (doFiltering && callback) {
            callback()
        }

        filteredItems = doFiltering
            ? items.filter((item) => {
                  let _filtered = true
                  Object.keys(newFilter).forEach((key) => {
                      const vKey = keys[key]
                      const itemVal = _get(item, vKey)
                      if (vKey && newFilter[key].length) {
                          _filtered =
                              _filtered &&
                              newFilter[key].some(
                                  (v) => itemVal == v || (Array.isArray(itemVal) && itemVal.includes(v))
                              )
                      }
                  })
                  return _filtered
              })
            : [...items]
        // console.log("doFiltering", filteredItems)

        return { filteredItems, newFilter }
    } else {
        return { filteredItems: [...items] }
    }
}

export function filter2Hash(filter: filterMap, navigate?: boolean): string {
    const urlHash = Object.keys(filter)
        .map((key) => {
            return filter[key].length ? key + "=" + filter[key].join(",") : ""
        })
        .filter((v) => v)
        .join("&")

    if (navigate) {
        const currentHash = get(location).hash.replace(/^#/, "")
        if (currentHash !== urlHash) {
            if (urlHash) {
                spaNavigate(get(location).path + "#" + urlHash, { replace: true })
            } else {
                spaNavigate(get(location).path, { replace: true })
            }
        }
    }
    return urlHash
}

export const cryptchaSolution = writable("")
export const cryptchaSolutionId = writable("")
let cryptcha: Cryptcha
let cryptchaTarget: HTMLDivElement
export async function initCryptcha(target: HTMLElement) {
    if (!cryptcha) {
        // create new instance
        cryptchaTarget = document.createElement("div")
        cryptcha = new Cryptcha({
            siteId: cryptchaSiteId,
            target: cryptchaTarget,
            baseUrl: "https://cryptcha.webmakers.de/api/command",
            log: false,
            autoSolve: true,
            onSolved({ solution, solutionId }) {
                cryptchaSolution.set(solution)
                cryptchaSolutionId.set(solutionId)
            },
        })
    }

    if (target) {
        target.innerHTML = ""
        target.appendChild(cryptchaTarget)
    }
}

export function resetCryptcha() {
    cryptcha = null
    cryptchaSolution.set("")
    cryptchaSolutionId.set("")
}

export function parsePriceTag(price: number | string): string {
    if (typeof price === "string") price = parseFloat(price)

    return `${price.toFixed(2).replace(".", ",")} €`
}

export function getVariableNameForChapter(chapter: number) {
    let colorName
    if (chapter == 1) {
        colorName = "--krass-kraft-primary"
    } else if (chapter == 2) {
        colorName = "--crazy-calm-primary"
    } else if (chapter == 3) {
        colorName = "--crazy-crave-control-primary"
    } else if (chapter == 4) {
        colorName = "--krass-kreativ-primary"
    }
    return colorName
}
export function getCalendarWeekFromDate(date: string | Date) {
    const dateObj = new Date(date)
    const onejan = new Date(dateObj.getFullYear(), 0, 1)
    return Math.ceil(((dateObj.getTime() - onejan.getTime()) / 86400000 + onejan.getDay() + 1) / 7)
}
