import _request from 'request-promise'
import cheerio from 'cheerio'
import {URL} from 'url'

const jar = _request.jar()
const request = _request.defaults({
  headers: {'Content-Type': 'application/json'},
  jar,
})

const SCV='https://www.alza.sk/Services/EShopService.svc/'

export async function login(credentials) {
  return await request.post(`${SCV}LoginUser`, {body: JSON.stringify(credentials)})
}

function getId(urlString) {
  const url = new URL(urlString)
  if (!url.hostname.endsWith('alza.sk')) throw new Error(`Invalid alza url: ${urlString}`)
  const dq = url.searchParams.get('dq')
  if (dq) return dq

  return url.pathname.match(/d(\d*)(\.htm)?$/)[1]
}

export async function addToCart(id, count) {
  return await request.post(`${SCV}OrderCommodity`, {body: JSON.stringify(
    {id, count}
  )})
}

export async function getInfo(url) {
  url = url.replace('m.alza.sk', 'alza.sk')
  const $ = cheerio.load(await request(url))
  const name = (
    $('meta[name="twitter:title"]').attr('content') ||
    $('meta[property="og:title"]').attr('content')
  ).replace(/\| Alza.sk\s*$/, '').trim().replace(/\s+/g, ' ')

  const price =parseFloat((
    $('span.price_withoutVat').text() ||
    $('tr.pricenormal').find('td.c2').find('span').text()
  ).replace(/[^\d,]/g, '').replace(/,/g, '.')
  )
  const description = $('div.nameextc').text()

  return {id: getId(url), name, price, description}
}

@@ -97,28 +97,159 @@
 nst 
-jar = _request.jar()
+BASE_URL = 'https://www.alza.sk/'%0A%0Aconst jar = _request.jar()%0Ajar.setCookie(_request.cookie(%60refer3=$%7BencodeURIComponent(%60$%7BBASE_URL%7D;%60)%7D%60), BASE_URL)%0A
 %0Acon
@@ -293,16 +293,21 @@
 aders: %7B
+%0A    
 'Content
@@ -332,16 +332,43 @@
 on/json'
+,%0A    referer: BASE_URL,%0A  
 %7D,%0A  jar
@@ -383,37 +383,28 @@
 nst SCV=
-'https://www.alza.sk/
+%60$%7BBASE_URL%7D
 Services
@@ -421,17 +421,17 @@
 ice.svc/
-'
+%60
 %0A%0Aexport

fix alza login